blob: f438253761dd98ef220c40f65adf306b4bbcdf6e [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"
michaelbai@google.com2251c622011-06-22 07:34:50 +090027#elif !defined(OS_ANDROID)
evan@chromium.org73aec0e2010-04-23 08:28:05 +090028#include <glib.h>
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"
brettw@chromium.org5b5f5e02011-01-01 10:01:06 +090046#include "base/threading/thread_restrictions.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090047#include "base/time/time.h"
estade@chromium.org868ecbc2009-06-24 12:29:26 +090048
michaelbai@google.com2251c622011-06-22 07:34:50 +090049#if defined(OS_ANDROID)
50#include "base/os_compat_android.h"
51#endif
52
qsr@chromium.org4ab5de92012-07-09 23:40:39 +090053#if !defined(OS_IOS)
54#include <grp.h>
55#endif
56
haruki@chromium.org712ff262012-08-06 18:14:44 +090057#if defined(OS_CHROMEOS)
58#include "base/chromeos/chromeos_version.h"
59#endif
60
brettw@chromium.org99b198e2013-04-12 14:17:15 +090061namespace base {
62
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090063namespace {
64
rsesek@chromium.orgdc818ac2012-07-20 07:24:02 +090065#if defined(OS_BSD) || defined(OS_MACOSX)
skerner@google.com93449ef2011-09-22 23:47:18 +090066typedef struct stat stat_wrapper_t;
67static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090068 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090069 return stat(path, sb);
70}
71static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090072 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090073 return lstat(path, sb);
74}
75#else
76typedef struct stat64 stat_wrapper_t;
77static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090078 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090079 return stat64(path, sb);
80}
81static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090082 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090083 return lstat64(path, sb);
84}
85#endif
86
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090087// Helper for NormalizeFilePath(), defined below.
88bool RealPath(const FilePath& path, FilePath* real_path) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090089 ThreadRestrictions::AssertIOAllowed(); // For realpath().
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090090 FilePath::CharType buf[PATH_MAX];
91 if (!realpath(path.value().c_str(), buf))
92 return false;
93
94 *real_path = FilePath(buf);
95 return true;
96}
97
skerner@google.com93449ef2011-09-22 23:47:18 +090098// Helper for VerifyPathControlledByUser.
99bool VerifySpecificPathControlledByUser(const FilePath& path,
100 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900101 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900102 stat_wrapper_t stat_info;
103 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900104 DPLOG(ERROR) << "Failed to get information on path "
105 << path.value();
skerner@google.com93449ef2011-09-22 23:47:18 +0900106 return false;
107 }
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900108
skerner@google.com93449ef2011-09-22 23:47:18 +0900109 if (S_ISLNK(stat_info.st_mode)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900110 DLOG(ERROR) << "Path " << path.value()
skerner@google.com93449ef2011-09-22 23:47:18 +0900111 << " is a symbolic link.";
112 return false;
113 }
114
115 if (stat_info.st_uid != owner_uid) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900116 DLOG(ERROR) << "Path " << path.value()
117 << " is owned by the wrong user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900118 return false;
119 }
120
skerner@chromium.org80784142011-10-18 06:30:29 +0900121 if ((stat_info.st_mode & S_IWGRP) &&
122 !ContainsKey(group_gids, stat_info.st_gid)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900123 DLOG(ERROR) << "Path " << path.value()
124 << " is writable by an unprivileged group.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900125 return false;
126 }
127
128 if (stat_info.st_mode & S_IWOTH) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900129 DLOG(ERROR) << "Path " << path.value()
130 << " is writable by any user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900131 return false;
132 }
133
134 return true;
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900135}
skerner@google.com93449ef2011-09-22 23:47:18 +0900136
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900137std::string TempFileName() {
138#if defined(OS_MACOSX)
139 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
140#endif
141
142#if defined(GOOGLE_CHROME_BUILD)
143 return std::string(".com.google.Chrome.XXXXXX");
144#else
145 return std::string(".org.chromium.Chromium.XXXXXX");
146#endif
147}
148
skerner@google.com93449ef2011-09-22 23:47:18 +0900149} // namespace
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900150
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900151FilePath MakeAbsoluteFilePath(const FilePath& input) {
152 ThreadRestrictions::AssertIOAllowed();
153 char full_path[PATH_MAX];
154 if (realpath(input.value().c_str(), full_path) == NULL)
155 return FilePath();
156 return FilePath(full_path);
mark@chromium.org13aa8aa2011-04-22 13:15:13 +0900157}
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900158
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900159// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
160// which works both with and without the recursive flag. I'm not sure we need
161// that functionality. If not, remove from file_util_win.cc, otherwise add it
162// here.
evanm@google.com874d1672008-10-31 08:54:04 +0900163bool Delete(const FilePath& path, bool recursive) {
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900164 ThreadRestrictions::AssertIOAllowed();
evanm@google.com874d1672008-10-31 08:54:04 +0900165 const char* path_str = path.value().c_str();
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900166 stat_wrapper_t file_info;
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900167 int test = CallLstat(path_str, &file_info);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900168 if (test != 0) {
169 // The Windows version defines this condition as success.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900170 bool ret = (errno == ENOENT || errno == ENOTDIR);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900171 return ret;
172 }
173 if (!S_ISDIR(file_info.st_mode))
evanm@google.com874d1672008-10-31 08:54:04 +0900174 return (unlink(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900175 if (!recursive)
evanm@google.com874d1672008-10-31 08:54:04 +0900176 return (rmdir(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900177
178 bool success = true;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900179 std::stack<std::string> directories;
180 directories.push(path.value());
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900181 FileEnumerator traversal(path, true,
182 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
183 FileEnumerator::SHOW_SYM_LINKS);
thestig@chromium.org3217c822009-08-07 06:23:07 +0900184 for (FilePath current = traversal.Next(); success && !current.empty();
185 current = traversal.Next()) {
brettw@chromium.org56946722013-06-08 13:53:36 +0900186 if (traversal.GetInfo().IsDirectory())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900187 directories.push(current.value());
188 else
189 success = (unlink(current.value().c_str()) == 0);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900190 }
thestig@chromium.org3217c822009-08-07 06:23:07 +0900191
192 while (success && !directories.empty()) {
193 FilePath dir = FilePath(directories.top());
194 directories.pop();
195 success = (rmdir(dir.value().c_str()) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900196 }
197 return success;
198}
199
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900200bool ReplaceFile(const FilePath& from_path,
201 const FilePath& to_path,
202 PlatformFileError* error) {
203 ThreadRestrictions::AssertIOAllowed();
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900204 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
205 return true;
206 if (error)
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900207 *error = ErrnoToPlatformFileError(errno);
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900208 return false;
phajdan.jr@chromium.orgd86bea02009-05-20 02:21:07 +0900209}
210
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900211bool CopyDirectory(const FilePath& from_path,
212 const FilePath& to_path,
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900213 bool recursive) {
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900214 ThreadRestrictions::AssertIOAllowed();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900215 // Some old callers of CopyDirectory want it to support wildcards.
216 // After some discussion, we decided to fix those callers.
217 // Break loudly here if anyone tries to do this.
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900218 // TODO(evanm): remove this once we're sure it's ok.
evanm@google.com874d1672008-10-31 08:54:04 +0900219 DCHECK(to_path.value().find('*') == std::string::npos);
220 DCHECK(from_path.value().find('*') == std::string::npos);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900221
222 char top_dir[PATH_MAX];
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900223 if (strlcpy(top_dir, from_path.value().c_str(),
224 arraysize(top_dir)) >= arraysize(top_dir)) {
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900225 return false;
226 }
227
thestig@chromium.org3217c822009-08-07 06:23:07 +0900228 // This function does not properly handle destinations within the source
229 FilePath real_to_path = to_path;
brettw@chromium.org10b64122013-07-12 02:36:07 +0900230 if (PathExists(real_to_path)) {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900231 real_to_path = MakeAbsoluteFilePath(real_to_path);
232 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900233 return false;
234 } else {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900235 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
236 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900237 return false;
238 }
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900239 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
240 if (real_from_path.empty())
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900241 return false;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900242 if (real_to_path.value().size() >= real_from_path.value().size() &&
243 real_to_path.value().compare(0, real_from_path.value().size(),
244 real_from_path.value()) == 0)
245 return false;
246
247 bool success = true;
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900248 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900249 if (recursive)
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900250 traverse_type |= FileEnumerator::DIRECTORIES;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900251 FileEnumerator traversal(from_path, recursive, traverse_type);
252
vandebo@chromium.org70cf3f12009-10-14 02:57:27 +0900253 // We have to mimic windows behavior here. |to_path| may not exist yet,
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900254 // start the loop with |to_path|.
brettw@chromium.org56946722013-06-08 13:53:36 +0900255 struct stat from_stat;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900256 FilePath current = from_path;
brettw@chromium.org56946722013-06-08 13:53:36 +0900257 if (stat(from_path.value().c_str(), &from_stat) < 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900258 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
259 << from_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900260 success = false;
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900261 }
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900262 struct stat to_path_stat;
263 FilePath from_path_base = from_path;
264 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
265 S_ISDIR(to_path_stat.st_mode)) {
266 // If the destination already exists and is a directory, then the
267 // top level of source needs to be copied.
268 from_path_base = from_path.DirName();
269 }
270
271 // The Windows version of this function assumes that non-recursive calls
272 // will always have a directory for from_path.
brettw@chromium.org56946722013-06-08 13:53:36 +0900273 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900274
thestig@chromium.org3217c822009-08-07 06:23:07 +0900275 while (success && !current.empty()) {
aedla@chromium.orgfef1a202013-01-30 20:38:02 +0900276 // current is the source path, including from_path, so append
277 // the suffix after from_path to to_path to create the target_path.
278 FilePath target_path(to_path);
279 if (from_path_base != current) {
280 if (!from_path_base.AppendRelativePath(current, &target_path)) {
281 success = false;
282 break;
283 }
phajdan.jr@chromium.orgecf50752009-01-14 03:57:46 +0900284 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900285
brettw@chromium.org56946722013-06-08 13:53:36 +0900286 if (S_ISDIR(from_stat.st_mode)) {
287 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
thestig@chromium.org3217c822009-08-07 06:23:07 +0900288 errno != EEXIST) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900289 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
290 << target_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900291 success = false;
292 }
brettw@chromium.org56946722013-06-08 13:53:36 +0900293 } else if (S_ISREG(from_stat.st_mode)) {
thestig@chromium.org3217c822009-08-07 06:23:07 +0900294 if (!CopyFile(current, target_path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900295 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
296 << target_path.value();
thestig@chromium.org3217c822009-08-07 06:23:07 +0900297 success = false;
298 }
299 } else {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900300 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
301 << current.value();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900302 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900303
thestig@chromium.org3217c822009-08-07 06:23:07 +0900304 current = traversal.Next();
brettw@chromium.org56946722013-06-08 13:53:36 +0900305 if (!current.empty())
306 from_stat = traversal.GetInfo().stat();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900307 }
308
thestig@chromium.org3217c822009-08-07 06:23:07 +0900309 return success;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900310}
311
brettw@chromium.org10b64122013-07-12 02:36:07 +0900312bool PathExists(const FilePath& path) {
313 ThreadRestrictions::AssertIOAllowed();
314 return access(path.value().c_str(), F_OK) == 0;
315}
316
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900317} // namespace base
318
319// -----------------------------------------------------------------------------
320
321namespace file_util {
322
323using base::stat_wrapper_t;
324using base::CallStat;
325using base::CallLstat;
326using base::FileEnumerator;
327using base::FilePath;
328using base::MakeAbsoluteFilePath;
329using base::RealPath;
330using base::VerifySpecificPathControlledByUser;
331
erikkay@google.comcce83822008-12-24 05:20:10 +0900332bool PathIsWritable(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900333 base::ThreadRestrictions::AssertIOAllowed();
agl@chromium.org41e00622010-05-18 00:01:22 +0900334 return access(path.value().c_str(), W_OK) == 0;
erikkay@google.comcce83822008-12-24 05:20:10 +0900335}
336
evanm@google.com874d1672008-10-31 08:54:04 +0900337bool DirectoryExists(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900338 base::ThreadRestrictions::AssertIOAllowed();
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900339 stat_wrapper_t file_info;
340 if (CallStat(path.value().c_str(), &file_info) == 0)
mmoss@google.com733df6b2008-09-12 01:09:11 +0900341 return S_ISDIR(file_info.st_mode);
342 return false;
343}
344
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900345bool ReadFromFD(int fd, char* buffer, size_t bytes) {
346 size_t total_read = 0;
347 while (total_read < bytes) {
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900348 ssize_t bytes_read =
349 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
350 if (bytes_read <= 0)
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900351 break;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900352 total_read += bytes_read;
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900353 }
354 return total_read == bytes;
355}
356
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900357bool CreateSymbolicLink(const FilePath& target_path,
358 const FilePath& symlink_path) {
359 DCHECK(!symlink_path.empty());
360 DCHECK(!target_path.empty());
361 return ::symlink(target_path.value().c_str(),
362 symlink_path.value().c_str()) != -1;
363}
364
365bool ReadSymbolicLink(const FilePath& symlink_path,
366 FilePath* target_path) {
367 DCHECK(!symlink_path.empty());
368 DCHECK(target_path);
369 char buf[PATH_MAX];
370 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
371
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900372 if (count <= 0) {
373 target_path->clear();
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900374 return false;
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900375 }
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900376
377 *target_path = FilePath(FilePath::StringType(buf, count));
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900378 return true;
379}
380
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900381bool GetPosixFilePermissions(const FilePath& path, int* mode) {
382 base::ThreadRestrictions::AssertIOAllowed();
383 DCHECK(mode);
384
385 stat_wrapper_t file_info;
386 // Uses stat(), because on symbolic link, lstat() does not return valid
387 // permission bits in st_mode
388 if (CallStat(path.value().c_str(), &file_info) != 0)
389 return false;
390
391 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
392 return true;
393}
394
395bool SetPosixFilePermissions(const FilePath& path,
396 int mode) {
397 base::ThreadRestrictions::AssertIOAllowed();
398 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
399
400 // Calls stat() so that we can preserve the higher bits like S_ISGID.
401 stat_wrapper_t stat_buf;
402 if (CallStat(path.value().c_str(), &stat_buf) != 0)
403 return false;
404
405 // Clears the existing permission bits, and adds the new ones.
406 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
407 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
408
409 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
410 return false;
411
412 return true;
413}
414
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900415// Creates and opens a temporary file in |directory|, returning the
erikkay@chromium.org3a9a6422009-09-12 02:33:50 +0900416// file descriptor. |path| is set to the temporary file path.
417// This function does NOT unlink() the file.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900418int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900419 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900420 *path = directory.Append(base::TempFileName());
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900421 const std::string& tmpdir_string = path->value();
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900422 // this should be OK since mkstemp just replaces characters in place
423 char* buffer = const_cast<char*>(tmpdir_string.c_str());
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900424
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900425 return HANDLE_EINTR(mkstemp(buffer));
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900426}
427
erikkay@chromium.org18f0dde2009-08-19 01:07:55 +0900428bool CreateTemporaryFile(FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900429 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900430 FilePath directory;
431 if (!GetTempDir(&directory))
432 return false;
433 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900434 if (fd < 0)
435 return false;
phajdan.jr@chromium.orgcad925c2011-04-12 15:51:22 +0900436 ignore_result(HANDLE_EINTR(close(fd)));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900437 return true;
438}
439
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900440FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900441 FilePath directory;
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900442 if (!GetShmemTempDir(&directory, executable))
evan@chromium.org2abe0b42010-06-11 07:56:23 +0900443 return NULL;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900444
phajdan.jr@chromium.org8139fe12009-04-28 15:50:36 +0900445 return CreateAndOpenTemporaryFileInDir(directory, path);
446}
447
448FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
449 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900450 if (fd < 0)
451 return NULL;
452
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900453 FILE* file = fdopen(fd, "a+");
454 if (!file)
455 ignore_result(HANDLE_EINTR(close(fd)));
456 return file;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900457}
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900458
459bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900460 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900461 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900462 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
jcampan@chromium.orgbf29e602008-10-11 03:50:32 +0900463}
464
skerner@chromium.orge4432392010-05-01 02:00:09 +0900465static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
466 const FilePath::StringType& name_tmpl,
467 FilePath* new_dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900468 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900469 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
470 << "Directory name template must contain \"XXXXXX\".";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900471
472 FilePath sub_dir = base_dir.Append(name_tmpl);
473 std::string sub_dir_string = sub_dir.value();
474
475 // this should be OK since mkdtemp just replaces characters in place
476 char* buffer = const_cast<char*>(sub_dir_string.c_str());
477 char* dtemp = mkdtemp(buffer);
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900478 if (!dtemp) {
479 DPLOG(ERROR) << "mkdtemp";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900480 return false;
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900481 }
skerner@chromium.orge4432392010-05-01 02:00:09 +0900482 *new_dir = FilePath(dtemp);
483 return true;
484}
485
486bool CreateTemporaryDirInDir(const FilePath& base_dir,
487 const FilePath::StringType& prefix,
skerner@chromium.orgbd112ab2010-06-30 16:19:11 +0900488 FilePath* new_dir) {
skerner@chromium.orge4432392010-05-01 02:00:09 +0900489 FilePath::StringType mkdtemp_template = prefix;
490 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
491 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
492}
493
erikkay@google.comcce83822008-12-24 05:20:10 +0900494bool CreateNewTempDirectory(const FilePath::StringType& prefix,
495 FilePath* new_temp_path) {
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900496 FilePath tmpdir;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900497 if (!GetTempDir(&tmpdir))
498 return false;
skerner@chromium.orge4432392010-05-01 02:00:09 +0900499
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900500 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
501 new_temp_path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900502}
503
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900504bool CreateDirectoryAndGetError(const FilePath& full_path,
505 base::PlatformFileError* error) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900506 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
evanm@google.com874d1672008-10-31 08:54:04 +0900507 std::vector<FilePath> subpaths;
508
509 // Collect a list of all parent directories.
510 FilePath last_path = full_path;
511 subpaths.push_back(full_path);
512 for (FilePath path = full_path.DirName();
513 path.value() != last_path.value(); path = path.DirName()) {
514 subpaths.push_back(path);
515 last_path = path;
516 }
517
518 // Iterate through the parents and create the missing ones.
519 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
520 i != subpaths.rend(); ++i) {
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900521 if (DirectoryExists(*i))
522 continue;
523 if (mkdir(i->value().c_str(), 0700) == 0)
524 continue;
525 // Mkdir failed, but it might have failed with EEXIST, or some other error
526 // due to the the directory appearing out of thin air. This can occur if
527 // two processes are trying to create the same file system tree at the same
528 // time. Check to see if it exists and make sure it is a directory.
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900529 int saved_errno = errno;
530 if (!DirectoryExists(*i)) {
531 if (error)
532 *error = base::ErrnoToPlatformFileError(saved_errno);
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900533 return false;
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900534 }
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900535 }
536 return true;
537}
538
jeremya@chromium.org05609662013-04-04 18:05:21 +0900539base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
540 const int kMaxAttempts = 20;
541 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
dcheng@chromium.org8164c2c2013-04-09 17:46:45 +0900542 int uniquifier =
543 GetUniquePathNumber(path, base::FilePath::StringType());
jeremya@chromium.org05609662013-04-04 18:05:21 +0900544 if (uniquifier < 0)
545 break;
546 base::FilePath test_path = (uniquifier == 0) ? path :
547 path.InsertBeforeExtensionASCII(
548 base::StringPrintf(" (%d)", uniquifier));
549 if (mkdir(test_path.value().c_str(), 0777) == 0)
550 return test_path;
551 else if (errno != EEXIST)
552 break;
553 }
554 return base::FilePath();
555}
556
rkc@chromium.orga40af282011-06-01 08:10:06 +0900557// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
558// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
559bool IsLink(const FilePath& file_path) {
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900560 stat_wrapper_t st;
rkc@chromium.orga40af282011-06-01 08:10:06 +0900561 // If we can't lstat the file, it's safe to assume that the file won't at
562 // least be a 'followable' link.
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900563 if (CallLstat(file_path.value().c_str(), &st) != 0)
rkc@chromium.orga40af282011-06-01 08:10:06 +0900564 return false;
565
566 if (S_ISLNK(st.st_mode))
567 return true;
568 else
569 return false;
570}
571
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900572bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900573 stat_wrapper_t file_info;
574 if (CallStat(file_path.value().c_str(), &file_info) != 0)
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900575 return false;
darin@google.com7f479f22008-09-26 10:04:08 +0900576 results->is_directory = S_ISDIR(file_info.st_mode);
577 results->size = file_info.st_size;
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900578#if defined(OS_MACOSX)
579 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
580 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
581 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
582#elif defined(OS_ANDROID)
brettw@chromium.orgdbc9b5a2009-07-25 01:13:53 +0900583 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900584 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
585 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900586#else
587 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
588 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
589 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
590#endif
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900591 return true;
592}
593
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900594bool GetInode(const FilePath& path, ino_t* inode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900595 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900596 struct stat buffer;
597 int result = stat(path.value().c_str(), &buffer);
598 if (result < 0)
599 return false;
600
601 *inode = buffer.st_ino;
602 return true;
603}
604
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900605FILE* OpenFile(const std::string& filename, const char* mode) {
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900606 return OpenFile(FilePath(filename), mode);
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900607}
608
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900609FILE* OpenFile(const FilePath& filename, const char* mode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900610 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900611 FILE* result = NULL;
612 do {
613 result = fopen(filename.value().c_str(), mode);
614 } while (!result && errno == EINTR);
615 return result;
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900616}
617
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900618int ReadFile(const FilePath& filename, char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900619 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900620 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900621 if (fd < 0)
622 return -1;
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900623
evan@chromium.org36699862010-02-02 11:28:16 +0900624 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
625 if (int ret = HANDLE_EINTR(close(fd)) < 0)
626 return ret;
627 return bytes_read;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900628}
629
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900630int WriteFile(const FilePath& filename, const char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900631 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900632 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900633 if (fd < 0)
634 return -1;
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900635
evan@chromium.org36699862010-02-02 11:28:16 +0900636 int bytes_written = WriteFileDescriptor(fd, data, size);
637 if (int ret = HANDLE_EINTR(close(fd)) < 0)
638 return ret;
639 return bytes_written;
estade@chromium.org557da512009-09-16 09:29:22 +0900640}
641
642int WriteFileDescriptor(const int fd, const char* data, int size) {
643 // Allow for partial writes.
644 ssize_t bytes_written_total = 0;
645 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
646 bytes_written_total += bytes_written_partial) {
647 bytes_written_partial =
648 HANDLE_EINTR(write(fd, data + bytes_written_total,
649 size - bytes_written_total));
650 if (bytes_written_partial < 0)
651 return -1;
652 }
653
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900654 return bytes_written_total;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900655}
656
loislo@chromium.orgeae0dcb2012-04-29 21:57:10 +0900657int AppendToFile(const FilePath& filename, const char* data, int size) {
658 base::ThreadRestrictions::AssertIOAllowed();
659 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
660 if (fd < 0)
661 return -1;
662
663 int bytes_written = WriteFileDescriptor(fd, data, size);
664 if (int ret = HANDLE_EINTR(close(fd)) < 0)
665 return ret;
666 return bytes_written;
667}
668
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900669// Gets the current working directory for the process.
evanm@google.com874d1672008-10-31 08:54:04 +0900670bool GetCurrentDirectory(FilePath* dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900671 // getcwd can return ENOENT, which implies it checks against the disk.
672 base::ThreadRestrictions::AssertIOAllowed();
673
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900674 char system_buffer[PATH_MAX] = "";
evanm@google.com874d1672008-10-31 08:54:04 +0900675 if (!getcwd(system_buffer, sizeof(system_buffer))) {
676 NOTREACHED();
677 return false;
678 }
679 *dir = FilePath(system_buffer);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900680 return true;
681}
682
683// Sets the current working directory for the process.
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900684bool SetCurrentDirectory(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900685 base::ThreadRestrictions::AssertIOAllowed();
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900686 int ret = chdir(path.value().c_str());
687 return !ret;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900688}
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900689
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900690bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
691 FilePath real_path_result;
692 if (!RealPath(path, &real_path_result))
skerner@chromium.org559baa92010-05-13 00:13:57 +0900693 return false;
694
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900695 // To be consistant with windows, fail if |real_path_result| is a
696 // directory.
697 stat_wrapper_t file_info;
698 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
699 S_ISDIR(file_info.st_mode))
700 return false;
701
702 *normalized_path = real_path_result;
skerner@chromium.org559baa92010-05-13 00:13:57 +0900703 return true;
704}
705
evan@chromium.orgb9575332010-04-22 06:11:36 +0900706#if !defined(OS_MACOSX)
707bool GetTempDir(FilePath* path) {
708 const char* tmp = getenv("TMPDIR");
709 if (tmp)
710 *path = FilePath(tmp);
711 else
michaelbai@google.com2251c622011-06-22 07:34:50 +0900712#if defined(OS_ANDROID)
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +0900713 return PathService::Get(base::DIR_CACHE, path);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900714#else
evan@chromium.orgb9575332010-04-22 06:11:36 +0900715 *path = FilePath("/tmp");
michaelbai@google.com2251c622011-06-22 07:34:50 +0900716#endif
evan@chromium.orgb9575332010-04-22 06:11:36 +0900717 return true;
718}
719
michaelbai@google.com2251c622011-06-22 07:34:50 +0900720#if !defined(OS_ANDROID)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900721
robert.nagy@gmail.comea54e462011-10-25 07:05:27 +0900722#if defined(OS_LINUX)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900723// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
724// This depends on the mount options used for /dev/shm, which vary among
725// different Linux distributions and possibly local configuration. It also
726// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
727// but its kernel allows mprotect with PROT_EXEC anyway.
728
729namespace {
730
731bool DetermineDevShmExecutable() {
732 bool result = false;
733 FilePath path;
734 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
735 if (fd >= 0) {
736 ScopedFD shm_fd_closer(&fd);
737 Delete(path, false);
scr@chromium.orge7506992011-12-23 07:31:44 +0900738 long sysconf_result = sysconf(_SC_PAGESIZE);
739 CHECK_GE(sysconf_result, 0);
740 size_t pagesize = static_cast<size_t>(sysconf_result);
741 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900742 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
743 if (mapping != MAP_FAILED) {
744 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
745 result = true;
746 munmap(mapping, pagesize);
747 }
748 }
749 return result;
evan@chromium.orgb9575332010-04-22 06:11:36 +0900750}
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900751
752}; // namespace
753#endif // defined(OS_LINUX)
754
755bool GetShmemTempDir(FilePath* path, bool executable) {
756#if defined(OS_LINUX)
757 bool use_dev_shm = true;
758 if (executable) {
759 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
760 use_dev_shm = s_dev_shm_executable;
761 }
762 if (use_dev_shm) {
763 *path = FilePath("/dev/shm");
764 return true;
765 }
michaelbai@google.com2251c622011-06-22 07:34:50 +0900766#endif
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900767 return GetTempDir(path);
768}
769#endif // !defined(OS_ANDROID)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900770
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900771FilePath GetHomeDir() {
haruki@chromium.org712ff262012-08-06 18:14:44 +0900772#if defined(OS_CHROMEOS)
773 if (base::chromeos::IsRunningOnChromeOS())
774 return FilePath("/home/chronos/user");
775#endif
776
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900777 const char* home_dir = getenv("HOME");
778 if (home_dir && home_dir[0])
779 return FilePath(home_dir);
780
michaelbai@google.com2251c622011-06-22 07:34:50 +0900781#if defined(OS_ANDROID)
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900782 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
michaelbai@google.com2251c622011-06-22 07:34:50 +0900783#else
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900784 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
785 base::ThreadRestrictions::AssertIOAllowed();
786
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900787 home_dir = g_get_home_dir();
788 if (home_dir && home_dir[0])
789 return FilePath(home_dir);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900790#endif
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900791
792 FilePath rv;
793 if (file_util::GetTempDir(&rv))
794 return rv;
795
796 // Last resort.
797 return FilePath("/tmp");
798}
thorogood@chromium.orge77009d2012-07-23 17:22:44 +0900799#endif // !defined(OS_MACOSX)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900800
skerner@google.com93449ef2011-09-22 23:47:18 +0900801bool VerifyPathControlledByUser(const FilePath& base,
802 const FilePath& path,
803 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900804 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900805 if (base != path && !base.IsParent(path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900806 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
807 << base.value() << "\", path = \"" << path.value() << "\"";
skerner@google.com93449ef2011-09-22 23:47:18 +0900808 return false;
809 }
810
811 std::vector<FilePath::StringType> base_components;
812 std::vector<FilePath::StringType> path_components;
813
814 base.GetComponents(&base_components);
815 path.GetComponents(&path_components);
816
817 std::vector<FilePath::StringType>::const_iterator ib, ip;
818 for (ib = base_components.begin(), ip = path_components.begin();
819 ib != base_components.end(); ++ib, ++ip) {
820 // |base| must be a subpath of |path|, so all components should match.
821 // If these CHECKs fail, look at the test that base is a parent of
822 // path at the top of this function.
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900823 DCHECK(ip != path_components.end());
824 DCHECK(*ip == *ib);
skerner@google.com93449ef2011-09-22 23:47:18 +0900825 }
826
827 FilePath current_path = base;
skerner@chromium.org80784142011-10-18 06:30:29 +0900828 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900829 return false;
830
831 for (; ip != path_components.end(); ++ip) {
832 current_path = current_path.Append(*ip);
skerner@chromium.org80784142011-10-18 06:30:29 +0900833 if (!VerifySpecificPathControlledByUser(
834 current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900835 return false;
836 }
837 return true;
838}
839
qsr@chromium.org4ab5de92012-07-09 23:40:39 +0900840#if defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900841bool VerifyPathControlledByAdmin(const FilePath& path) {
842 const unsigned kRootUid = 0;
843 const FilePath kFileSystemRoot("/");
844
845 // The name of the administrator group on mac os.
skerner@chromium.org80784142011-10-18 06:30:29 +0900846 const char* const kAdminGroupNames[] = {
847 "admin",
848 "wheel"
849 };
skerner@google.com93449ef2011-09-22 23:47:18 +0900850
851 // Reading the groups database may touch the file system.
852 base::ThreadRestrictions::AssertIOAllowed();
853
skerner@chromium.org80784142011-10-18 06:30:29 +0900854 std::set<gid_t> allowed_group_ids;
855 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
856 struct group *group_record = getgrnam(kAdminGroupNames[i]);
857 if (!group_record) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900858 DPLOG(ERROR) << "Could not get the group ID of group \""
859 << kAdminGroupNames[i] << "\".";
skerner@chromium.org80784142011-10-18 06:30:29 +0900860 continue;
861 }
862
863 allowed_group_ids.insert(group_record->gr_gid);
skerner@google.com93449ef2011-09-22 23:47:18 +0900864 }
865
866 return VerifyPathControlledByUser(
skerner@chromium.org80784142011-10-18 06:30:29 +0900867 kFileSystemRoot, path, kRootUid, allowed_group_ids);
skerner@google.com93449ef2011-09-22 23:47:18 +0900868}
stuartmorgan@chromium.org925e0b72012-07-24 20:23:32 +0900869#endif // defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900870
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900871int GetMaximumPathComponentLength(const FilePath& path) {
872 base::ThreadRestrictions::AssertIOAllowed();
873 return pathconf(path.value().c_str(), _PC_NAME_MAX);
874}
875
thestig@chromium.org7ecbbc12010-11-20 12:38:15 +0900876} // namespace file_util
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900877
878namespace base {
879namespace internal {
880
881bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
882 ThreadRestrictions::AssertIOAllowed();
883 // Windows compatibility: if to_path exists, from_path and to_path
884 // must be the same type, either both files, or both directories.
885 stat_wrapper_t to_file_info;
886 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
887 stat_wrapper_t from_file_info;
888 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
889 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
890 return false;
891 } else {
892 return false;
893 }
894 }
895
896 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
897 return true;
898
899 if (!CopyDirectory(from_path, to_path, true))
900 return false;
901
902 Delete(from_path, true);
903 return true;
904}
905
906#if !defined(OS_MACOSX)
907// Mac has its own implementation, this is for all other Posix systems.
908bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
909 ThreadRestrictions::AssertIOAllowed();
910 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
911 if (infile < 0)
912 return false;
913
914 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
915 if (outfile < 0) {
916 ignore_result(HANDLE_EINTR(close(infile)));
917 return false;
918 }
919
920 const size_t kBufferSize = 32768;
921 std::vector<char> buffer(kBufferSize);
922 bool result = true;
923
924 while (result) {
925 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
926 if (bytes_read < 0) {
927 result = false;
928 break;
929 }
930 if (bytes_read == 0)
931 break;
932 // Allow for partial writes
933 ssize_t bytes_written_per_read = 0;
934 do {
935 ssize_t bytes_written_partial = HANDLE_EINTR(write(
936 outfile,
937 &buffer[bytes_written_per_read],
938 bytes_read - bytes_written_per_read));
939 if (bytes_written_partial < 0) {
940 result = false;
941 break;
942 }
943 bytes_written_per_read += bytes_written_partial;
944 } while (bytes_written_per_read < bytes_read);
945 }
946
947 if (HANDLE_EINTR(close(infile)) < 0)
948 result = false;
949 if (HANDLE_EINTR(close(outfile)) < 0)
950 result = false;
951
952 return result;
953}
954#endif // !defined(OS_MACOSX)
955
956} // namespace internal
957} // namespace base