blob: 762700ae42c11d42e39bffaf89aaf4472a704dd9 [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.
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900163bool DeleteFile(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.org5a112e72013-07-16 05:18:09 +0900317bool PathIsWritable(const FilePath& path) {
318 ThreadRestrictions::AssertIOAllowed();
319 return access(path.value().c_str(), W_OK) == 0;
320}
321
322bool DirectoryExists(const FilePath& path) {
323 ThreadRestrictions::AssertIOAllowed();
324 stat_wrapper_t file_info;
325 if (CallStat(path.value().c_str(), &file_info) == 0)
326 return S_ISDIR(file_info.st_mode);
327 return false;
328}
329
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900330} // namespace base
331
332// -----------------------------------------------------------------------------
333
334namespace file_util {
335
336using base::stat_wrapper_t;
337using base::CallStat;
338using base::CallLstat;
brettw@chromium.org5a112e72013-07-16 05:18:09 +0900339using base::DirectoryExists;
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900340using base::FileEnumerator;
341using base::FilePath;
342using base::MakeAbsoluteFilePath;
343using base::RealPath;
344using base::VerifySpecificPathControlledByUser;
345
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900346bool ReadFromFD(int fd, char* buffer, size_t bytes) {
347 size_t total_read = 0;
348 while (total_read < bytes) {
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900349 ssize_t bytes_read =
350 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
351 if (bytes_read <= 0)
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900352 break;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900353 total_read += bytes_read;
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900354 }
355 return total_read == bytes;
356}
357
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900358bool CreateSymbolicLink(const FilePath& target_path,
359 const FilePath& symlink_path) {
360 DCHECK(!symlink_path.empty());
361 DCHECK(!target_path.empty());
362 return ::symlink(target_path.value().c_str(),
363 symlink_path.value().c_str()) != -1;
364}
365
366bool ReadSymbolicLink(const FilePath& symlink_path,
367 FilePath* target_path) {
368 DCHECK(!symlink_path.empty());
369 DCHECK(target_path);
370 char buf[PATH_MAX];
371 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
372
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900373 if (count <= 0) {
374 target_path->clear();
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900375 return false;
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900376 }
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900377
378 *target_path = FilePath(FilePath::StringType(buf, count));
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900379 return true;
380}
381
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900382bool GetPosixFilePermissions(const FilePath& path, int* mode) {
383 base::ThreadRestrictions::AssertIOAllowed();
384 DCHECK(mode);
385
386 stat_wrapper_t file_info;
387 // Uses stat(), because on symbolic link, lstat() does not return valid
388 // permission bits in st_mode
389 if (CallStat(path.value().c_str(), &file_info) != 0)
390 return false;
391
392 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
393 return true;
394}
395
396bool SetPosixFilePermissions(const FilePath& path,
397 int mode) {
398 base::ThreadRestrictions::AssertIOAllowed();
399 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
400
401 // Calls stat() so that we can preserve the higher bits like S_ISGID.
402 stat_wrapper_t stat_buf;
403 if (CallStat(path.value().c_str(), &stat_buf) != 0)
404 return false;
405
406 // Clears the existing permission bits, and adds the new ones.
407 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
408 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
409
410 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
411 return false;
412
413 return true;
414}
415
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900416// Creates and opens a temporary file in |directory|, returning the
erikkay@chromium.org3a9a6422009-09-12 02:33:50 +0900417// file descriptor. |path| is set to the temporary file path.
418// This function does NOT unlink() the file.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900419int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900420 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900421 *path = directory.Append(base::TempFileName());
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900422 const std::string& tmpdir_string = path->value();
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900423 // this should be OK since mkstemp just replaces characters in place
424 char* buffer = const_cast<char*>(tmpdir_string.c_str());
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900425
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900426 return HANDLE_EINTR(mkstemp(buffer));
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900427}
428
erikkay@chromium.org18f0dde2009-08-19 01:07:55 +0900429bool CreateTemporaryFile(FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900430 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900431 FilePath directory;
432 if (!GetTempDir(&directory))
433 return false;
434 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900435 if (fd < 0)
436 return false;
phajdan.jr@chromium.orgcad925c2011-04-12 15:51:22 +0900437 ignore_result(HANDLE_EINTR(close(fd)));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900438 return true;
439}
440
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900441FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900442 FilePath directory;
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900443 if (!GetShmemTempDir(&directory, executable))
evan@chromium.org2abe0b42010-06-11 07:56:23 +0900444 return NULL;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900445
phajdan.jr@chromium.org8139fe12009-04-28 15:50:36 +0900446 return CreateAndOpenTemporaryFileInDir(directory, path);
447}
448
449FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
450 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900451 if (fd < 0)
452 return NULL;
453
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900454 FILE* file = fdopen(fd, "a+");
455 if (!file)
456 ignore_result(HANDLE_EINTR(close(fd)));
457 return file;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900458}
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900459
460bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900461 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900462 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900463 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
jcampan@chromium.orgbf29e602008-10-11 03:50:32 +0900464}
465
skerner@chromium.orge4432392010-05-01 02:00:09 +0900466static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
467 const FilePath::StringType& name_tmpl,
468 FilePath* new_dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900469 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900470 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
471 << "Directory name template must contain \"XXXXXX\".";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900472
473 FilePath sub_dir = base_dir.Append(name_tmpl);
474 std::string sub_dir_string = sub_dir.value();
475
476 // this should be OK since mkdtemp just replaces characters in place
477 char* buffer = const_cast<char*>(sub_dir_string.c_str());
478 char* dtemp = mkdtemp(buffer);
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900479 if (!dtemp) {
480 DPLOG(ERROR) << "mkdtemp";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900481 return false;
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900482 }
skerner@chromium.orge4432392010-05-01 02:00:09 +0900483 *new_dir = FilePath(dtemp);
484 return true;
485}
486
487bool CreateTemporaryDirInDir(const FilePath& base_dir,
488 const FilePath::StringType& prefix,
skerner@chromium.orgbd112ab2010-06-30 16:19:11 +0900489 FilePath* new_dir) {
skerner@chromium.orge4432392010-05-01 02:00:09 +0900490 FilePath::StringType mkdtemp_template = prefix;
491 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
492 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
493}
494
erikkay@google.comcce83822008-12-24 05:20:10 +0900495bool CreateNewTempDirectory(const FilePath::StringType& prefix,
496 FilePath* new_temp_path) {
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900497 FilePath tmpdir;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900498 if (!GetTempDir(&tmpdir))
499 return false;
skerner@chromium.orge4432392010-05-01 02:00:09 +0900500
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900501 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
502 new_temp_path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900503}
504
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900505bool CreateDirectoryAndGetError(const FilePath& full_path,
506 base::PlatformFileError* error) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900507 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
evanm@google.com874d1672008-10-31 08:54:04 +0900508 std::vector<FilePath> subpaths;
509
510 // Collect a list of all parent directories.
511 FilePath last_path = full_path;
512 subpaths.push_back(full_path);
513 for (FilePath path = full_path.DirName();
514 path.value() != last_path.value(); path = path.DirName()) {
515 subpaths.push_back(path);
516 last_path = path;
517 }
518
519 // Iterate through the parents and create the missing ones.
520 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
521 i != subpaths.rend(); ++i) {
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900522 if (DirectoryExists(*i))
523 continue;
524 if (mkdir(i->value().c_str(), 0700) == 0)
525 continue;
526 // Mkdir failed, but it might have failed with EEXIST, or some other error
527 // due to the the directory appearing out of thin air. This can occur if
528 // two processes are trying to create the same file system tree at the same
529 // time. Check to see if it exists and make sure it is a directory.
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900530 int saved_errno = errno;
531 if (!DirectoryExists(*i)) {
532 if (error)
533 *error = base::ErrnoToPlatformFileError(saved_errno);
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900534 return false;
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900535 }
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900536 }
537 return true;
538}
539
jeremya@chromium.org05609662013-04-04 18:05:21 +0900540base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
541 const int kMaxAttempts = 20;
542 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
dcheng@chromium.org8164c2c2013-04-09 17:46:45 +0900543 int uniquifier =
544 GetUniquePathNumber(path, base::FilePath::StringType());
jeremya@chromium.org05609662013-04-04 18:05:21 +0900545 if (uniquifier < 0)
546 break;
547 base::FilePath test_path = (uniquifier == 0) ? path :
548 path.InsertBeforeExtensionASCII(
549 base::StringPrintf(" (%d)", uniquifier));
550 if (mkdir(test_path.value().c_str(), 0777) == 0)
551 return test_path;
552 else if (errno != EEXIST)
553 break;
554 }
555 return base::FilePath();
556}
557
rkc@chromium.orga40af282011-06-01 08:10:06 +0900558// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
559// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
560bool IsLink(const FilePath& file_path) {
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900561 stat_wrapper_t st;
rkc@chromium.orga40af282011-06-01 08:10:06 +0900562 // If we can't lstat the file, it's safe to assume that the file won't at
563 // least be a 'followable' link.
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900564 if (CallLstat(file_path.value().c_str(), &st) != 0)
rkc@chromium.orga40af282011-06-01 08:10:06 +0900565 return false;
566
567 if (S_ISLNK(st.st_mode))
568 return true;
569 else
570 return false;
571}
572
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900573bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900574 stat_wrapper_t file_info;
575 if (CallStat(file_path.value().c_str(), &file_info) != 0)
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900576 return false;
darin@google.com7f479f22008-09-26 10:04:08 +0900577 results->is_directory = S_ISDIR(file_info.st_mode);
578 results->size = file_info.st_size;
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900579#if defined(OS_MACOSX)
580 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
581 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
582 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
583#elif defined(OS_ANDROID)
brettw@chromium.orgdbc9b5a2009-07-25 01:13:53 +0900584 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900585 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
586 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900587#else
588 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
589 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
590 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
591#endif
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900592 return true;
593}
594
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900595bool GetInode(const FilePath& path, ino_t* inode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900596 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900597 struct stat buffer;
598 int result = stat(path.value().c_str(), &buffer);
599 if (result < 0)
600 return false;
601
602 *inode = buffer.st_ino;
603 return true;
604}
605
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900606FILE* OpenFile(const std::string& filename, const char* mode) {
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900607 return OpenFile(FilePath(filename), mode);
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900608}
609
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900610FILE* OpenFile(const FilePath& filename, const char* mode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900611 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900612 FILE* result = NULL;
613 do {
614 result = fopen(filename.value().c_str(), mode);
615 } while (!result && errno == EINTR);
616 return result;
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900617}
618
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900619int ReadFile(const FilePath& filename, char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900620 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900621 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900622 if (fd < 0)
623 return -1;
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900624
evan@chromium.org36699862010-02-02 11:28:16 +0900625 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
626 if (int ret = HANDLE_EINTR(close(fd)) < 0)
627 return ret;
628 return bytes_read;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900629}
630
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900631int WriteFile(const FilePath& filename, const char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900632 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900633 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900634 if (fd < 0)
635 return -1;
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900636
evan@chromium.org36699862010-02-02 11:28:16 +0900637 int bytes_written = WriteFileDescriptor(fd, data, size);
638 if (int ret = HANDLE_EINTR(close(fd)) < 0)
639 return ret;
640 return bytes_written;
estade@chromium.org557da512009-09-16 09:29:22 +0900641}
642
643int WriteFileDescriptor(const int fd, const char* data, int size) {
644 // Allow for partial writes.
645 ssize_t bytes_written_total = 0;
646 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
647 bytes_written_total += bytes_written_partial) {
648 bytes_written_partial =
649 HANDLE_EINTR(write(fd, data + bytes_written_total,
650 size - bytes_written_total));
651 if (bytes_written_partial < 0)
652 return -1;
653 }
654
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900655 return bytes_written_total;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900656}
657
loislo@chromium.orgeae0dcb2012-04-29 21:57:10 +0900658int AppendToFile(const FilePath& filename, const char* data, int size) {
659 base::ThreadRestrictions::AssertIOAllowed();
660 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
661 if (fd < 0)
662 return -1;
663
664 int bytes_written = WriteFileDescriptor(fd, data, size);
665 if (int ret = HANDLE_EINTR(close(fd)) < 0)
666 return ret;
667 return bytes_written;
668}
669
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900670// Gets the current working directory for the process.
evanm@google.com874d1672008-10-31 08:54:04 +0900671bool GetCurrentDirectory(FilePath* dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900672 // getcwd can return ENOENT, which implies it checks against the disk.
673 base::ThreadRestrictions::AssertIOAllowed();
674
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900675 char system_buffer[PATH_MAX] = "";
evanm@google.com874d1672008-10-31 08:54:04 +0900676 if (!getcwd(system_buffer, sizeof(system_buffer))) {
677 NOTREACHED();
678 return false;
679 }
680 *dir = FilePath(system_buffer);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900681 return true;
682}
683
684// Sets the current working directory for the process.
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900685bool SetCurrentDirectory(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900686 base::ThreadRestrictions::AssertIOAllowed();
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900687 int ret = chdir(path.value().c_str());
688 return !ret;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900689}
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900690
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900691bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
692 FilePath real_path_result;
693 if (!RealPath(path, &real_path_result))
skerner@chromium.org559baa92010-05-13 00:13:57 +0900694 return false;
695
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900696 // To be consistant with windows, fail if |real_path_result| is a
697 // directory.
698 stat_wrapper_t file_info;
699 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
700 S_ISDIR(file_info.st_mode))
701 return false;
702
703 *normalized_path = real_path_result;
skerner@chromium.org559baa92010-05-13 00:13:57 +0900704 return true;
705}
706
evan@chromium.orgb9575332010-04-22 06:11:36 +0900707#if !defined(OS_MACOSX)
708bool GetTempDir(FilePath* path) {
709 const char* tmp = getenv("TMPDIR");
710 if (tmp)
711 *path = FilePath(tmp);
712 else
michaelbai@google.com2251c622011-06-22 07:34:50 +0900713#if defined(OS_ANDROID)
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +0900714 return PathService::Get(base::DIR_CACHE, path);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900715#else
evan@chromium.orgb9575332010-04-22 06:11:36 +0900716 *path = FilePath("/tmp");
michaelbai@google.com2251c622011-06-22 07:34:50 +0900717#endif
evan@chromium.orgb9575332010-04-22 06:11:36 +0900718 return true;
719}
720
michaelbai@google.com2251c622011-06-22 07:34:50 +0900721#if !defined(OS_ANDROID)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900722
robert.nagy@gmail.comea54e462011-10-25 07:05:27 +0900723#if defined(OS_LINUX)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900724// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
725// This depends on the mount options used for /dev/shm, which vary among
726// different Linux distributions and possibly local configuration. It also
727// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
728// but its kernel allows mprotect with PROT_EXEC anyway.
729
730namespace {
731
732bool DetermineDevShmExecutable() {
733 bool result = false;
734 FilePath path;
735 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
736 if (fd >= 0) {
737 ScopedFD shm_fd_closer(&fd);
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900738 DeleteFile(path, false);
scr@chromium.orge7506992011-12-23 07:31:44 +0900739 long sysconf_result = sysconf(_SC_PAGESIZE);
740 CHECK_GE(sysconf_result, 0);
741 size_t pagesize = static_cast<size_t>(sysconf_result);
742 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900743 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
744 if (mapping != MAP_FAILED) {
745 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
746 result = true;
747 munmap(mapping, pagesize);
748 }
749 }
750 return result;
evan@chromium.orgb9575332010-04-22 06:11:36 +0900751}
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900752
753}; // namespace
754#endif // defined(OS_LINUX)
755
756bool GetShmemTempDir(FilePath* path, bool executable) {
757#if defined(OS_LINUX)
758 bool use_dev_shm = true;
759 if (executable) {
760 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
761 use_dev_shm = s_dev_shm_executable;
762 }
763 if (use_dev_shm) {
764 *path = FilePath("/dev/shm");
765 return true;
766 }
michaelbai@google.com2251c622011-06-22 07:34:50 +0900767#endif
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900768 return GetTempDir(path);
769}
770#endif // !defined(OS_ANDROID)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900771
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900772FilePath GetHomeDir() {
haruki@chromium.org712ff262012-08-06 18:14:44 +0900773#if defined(OS_CHROMEOS)
774 if (base::chromeos::IsRunningOnChromeOS())
775 return FilePath("/home/chronos/user");
776#endif
777
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900778 const char* home_dir = getenv("HOME");
779 if (home_dir && home_dir[0])
780 return FilePath(home_dir);
781
michaelbai@google.com2251c622011-06-22 07:34:50 +0900782#if defined(OS_ANDROID)
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900783 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
michaelbai@google.com2251c622011-06-22 07:34:50 +0900784#else
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900785 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
786 base::ThreadRestrictions::AssertIOAllowed();
787
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900788 home_dir = g_get_home_dir();
789 if (home_dir && home_dir[0])
790 return FilePath(home_dir);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900791#endif
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900792
793 FilePath rv;
794 if (file_util::GetTempDir(&rv))
795 return rv;
796
797 // Last resort.
798 return FilePath("/tmp");
799}
thorogood@chromium.orge77009d2012-07-23 17:22:44 +0900800#endif // !defined(OS_MACOSX)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900801
skerner@google.com93449ef2011-09-22 23:47:18 +0900802bool VerifyPathControlledByUser(const FilePath& base,
803 const FilePath& path,
804 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900805 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900806 if (base != path && !base.IsParent(path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900807 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
808 << base.value() << "\", path = \"" << path.value() << "\"";
skerner@google.com93449ef2011-09-22 23:47:18 +0900809 return false;
810 }
811
812 std::vector<FilePath::StringType> base_components;
813 std::vector<FilePath::StringType> path_components;
814
815 base.GetComponents(&base_components);
816 path.GetComponents(&path_components);
817
818 std::vector<FilePath::StringType>::const_iterator ib, ip;
819 for (ib = base_components.begin(), ip = path_components.begin();
820 ib != base_components.end(); ++ib, ++ip) {
821 // |base| must be a subpath of |path|, so all components should match.
822 // If these CHECKs fail, look at the test that base is a parent of
823 // path at the top of this function.
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900824 DCHECK(ip != path_components.end());
825 DCHECK(*ip == *ib);
skerner@google.com93449ef2011-09-22 23:47:18 +0900826 }
827
828 FilePath current_path = base;
skerner@chromium.org80784142011-10-18 06:30:29 +0900829 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900830 return false;
831
832 for (; ip != path_components.end(); ++ip) {
833 current_path = current_path.Append(*ip);
skerner@chromium.org80784142011-10-18 06:30:29 +0900834 if (!VerifySpecificPathControlledByUser(
835 current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900836 return false;
837 }
838 return true;
839}
840
qsr@chromium.org4ab5de92012-07-09 23:40:39 +0900841#if defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900842bool VerifyPathControlledByAdmin(const FilePath& path) {
843 const unsigned kRootUid = 0;
844 const FilePath kFileSystemRoot("/");
845
846 // The name of the administrator group on mac os.
skerner@chromium.org80784142011-10-18 06:30:29 +0900847 const char* const kAdminGroupNames[] = {
848 "admin",
849 "wheel"
850 };
skerner@google.com93449ef2011-09-22 23:47:18 +0900851
852 // Reading the groups database may touch the file system.
853 base::ThreadRestrictions::AssertIOAllowed();
854
skerner@chromium.org80784142011-10-18 06:30:29 +0900855 std::set<gid_t> allowed_group_ids;
856 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
857 struct group *group_record = getgrnam(kAdminGroupNames[i]);
858 if (!group_record) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900859 DPLOG(ERROR) << "Could not get the group ID of group \""
860 << kAdminGroupNames[i] << "\".";
skerner@chromium.org80784142011-10-18 06:30:29 +0900861 continue;
862 }
863
864 allowed_group_ids.insert(group_record->gr_gid);
skerner@google.com93449ef2011-09-22 23:47:18 +0900865 }
866
867 return VerifyPathControlledByUser(
skerner@chromium.org80784142011-10-18 06:30:29 +0900868 kFileSystemRoot, path, kRootUid, allowed_group_ids);
skerner@google.com93449ef2011-09-22 23:47:18 +0900869}
stuartmorgan@chromium.org925e0b72012-07-24 20:23:32 +0900870#endif // defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900871
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900872int GetMaximumPathComponentLength(const FilePath& path) {
873 base::ThreadRestrictions::AssertIOAllowed();
874 return pathconf(path.value().c_str(), _PC_NAME_MAX);
875}
876
thestig@chromium.org7ecbbc12010-11-20 12:38:15 +0900877} // namespace file_util
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900878
879namespace base {
880namespace internal {
881
882bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
883 ThreadRestrictions::AssertIOAllowed();
884 // Windows compatibility: if to_path exists, from_path and to_path
885 // must be the same type, either both files, or both directories.
886 stat_wrapper_t to_file_info;
887 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
888 stat_wrapper_t from_file_info;
889 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
890 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
891 return false;
892 } else {
893 return false;
894 }
895 }
896
897 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
898 return true;
899
900 if (!CopyDirectory(from_path, to_path, true))
901 return false;
902
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900903 DeleteFile(from_path, true);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900904 return true;
905}
906
907#if !defined(OS_MACOSX)
908// Mac has its own implementation, this is for all other Posix systems.
909bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
910 ThreadRestrictions::AssertIOAllowed();
911 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
912 if (infile < 0)
913 return false;
914
915 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
916 if (outfile < 0) {
917 ignore_result(HANDLE_EINTR(close(infile)));
918 return false;
919 }
920
921 const size_t kBufferSize = 32768;
922 std::vector<char> buffer(kBufferSize);
923 bool result = true;
924
925 while (result) {
926 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
927 if (bytes_read < 0) {
928 result = false;
929 break;
930 }
931 if (bytes_read == 0)
932 break;
933 // Allow for partial writes
934 ssize_t bytes_written_per_read = 0;
935 do {
936 ssize_t bytes_written_partial = HANDLE_EINTR(write(
937 outfile,
938 &buffer[bytes_written_per_read],
939 bytes_read - bytes_written_per_read));
940 if (bytes_written_partial < 0) {
941 result = false;
942 break;
943 }
944 bytes_written_per_read += bytes_written_partial;
945 } while (bytes_written_per_read < bytes_read);
946 }
947
948 if (HANDLE_EINTR(close(infile)) < 0)
949 result = false;
950 if (HANDLE_EINTR(close(outfile)) < 0)
951 result = false;
952
953 return result;
954}
955#endif // !defined(OS_MACOSX)
956
957} // namespace internal
958} // namespace base