blob: 134935c271774c6511ac66fc83fd312fc1c0e1c7 [file] [log] [blame]
tzik@chromium.orgf5864952012-03-10 09:18:31 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
mmentovai@google.comaa13be62008-09-03 03:20:34 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/file_util.h"
6
evan@chromium.org37301322009-04-21 10:50:39 +09007#include <dirent.h>
evanm@google.com5c1d39b2008-09-19 04:15:54 +09008#include <errno.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +09009#include <fcntl.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090010#include <libgen.h>
skerner@chromium.org5f3c4562010-05-13 06:36:39 +090011#include <limits.h>
mark@chromium.orgd1bafc62008-10-02 02:40:13 +090012#include <stdio.h>
evan@chromium.org73aec0e2010-04-23 08:28:05 +090013#include <stdlib.h>
evanm@google.com5c1d39b2008-09-19 04:15:54 +090014#include <string.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090015#include <sys/errno.h>
estade@chromium.org2c233532008-12-13 08:43:03 +090016#include <sys/mman.h>
skerner@chromium.org559baa92010-05-13 00:13:57 +090017#include <sys/param.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090018#include <sys/stat.h>
jochen@chromium.orga6879772010-02-18 19:02:26 +090019#include <sys/time.h>
evan@chromium.org37301322009-04-21 10:50:39 +090020#include <sys/types.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090021#include <time.h>
evan@chromium.org37301322009-04-21 10:50:39 +090022#include <unistd.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090023
mark@chromium.org0e56c162009-09-17 02:31:25 +090024#if defined(OS_MACOSX)
25#include <AvailabilityMacros.h>
mark@chromium.org13aa8aa2011-04-22 13:15:13 +090026#include "base/mac/foundation_util.h"
spang@chromium.org8d0fa9a2013-11-20 14:33:46 +090027#elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
satorux@chromium.org0c64e3e2013-11-07 20:38:32 +090028#include <glib.h> // for g_get_home_dir()
mark@chromium.org0e56c162009-09-17 02:31:25 +090029#endif
30
mmentovai@google.comaa13be62008-09-03 03:20:34 +090031#include <fstream>
32
33#include "base/basictypes.h"
brettw@chromium.org56946722013-06-08 13:53:36 +090034#include "base/files/file_enumerator.h"
brettw@chromium.org59eef1f2013-02-24 14:40:52 +090035#include "base/files/file_path.h"
mmentovai@google.comaa13be62008-09-03 03:20:34 +090036#include "base/logging.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090037#include "base/memory/scoped_ptr.h"
38#include "base/memory/singleton.h"
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +090039#include "base/path_service.h"
brettw@chromium.orgb1788fb2012-11-15 05:54:35 +090040#include "base/posix/eintr_wrapper.h"
skerner@chromium.org80784142011-10-18 06:30:29 +090041#include "base/stl_util.h"
avi@chromium.org94bd5732013-06-11 22:36:37 +090042#include "base/strings/string_util.h"
43#include "base/strings/stringprintf.h"
brettw@chromium.org1f67a912013-02-08 04:18:03 +090044#include "base/strings/sys_string_conversions.h"
avi@chromium.org17f60622013-06-08 03:37:07 +090045#include "base/strings/utf_string_conversions.h"
stevenjb@chromium.org861313b2013-09-28 04:28:24 +090046#include "base/sys_info.h"
brettw@chromium.org5b5f5e02011-01-01 10:01:06 +090047#include "base/threading/thread_restrictions.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090048#include "base/time/time.h"
estade@chromium.org868ecbc2009-06-24 12:29:26 +090049
michaelbai@google.com2251c622011-06-22 07:34:50 +090050#if defined(OS_ANDROID)
51#include "base/os_compat_android.h"
52#endif
53
qsr@chromium.org4ab5de92012-07-09 23:40:39 +090054#if !defined(OS_IOS)
55#include <grp.h>
56#endif
57
brettw@chromium.org99b198e2013-04-12 14:17:15 +090058namespace base {
59
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090060namespace {
61
rsesek@chromium.orgdc818ac2012-07-20 07:24:02 +090062#if defined(OS_BSD) || defined(OS_MACOSX)
skerner@google.com93449ef2011-09-22 23:47:18 +090063typedef struct stat stat_wrapper_t;
64static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090065 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090066 return stat(path, sb);
67}
68static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090069 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090070 return lstat(path, sb);
71}
72#else
73typedef struct stat64 stat_wrapper_t;
74static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090075 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090076 return stat64(path, sb);
77}
78static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090079 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090080 return lstat64(path, sb);
81}
82#endif
83
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090084// Helper for NormalizeFilePath(), defined below.
85bool RealPath(const FilePath& path, FilePath* real_path) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090086 ThreadRestrictions::AssertIOAllowed(); // For realpath().
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090087 FilePath::CharType buf[PATH_MAX];
88 if (!realpath(path.value().c_str(), buf))
89 return false;
90
91 *real_path = FilePath(buf);
92 return true;
93}
94
skerner@google.com93449ef2011-09-22 23:47:18 +090095// Helper for VerifyPathControlledByUser.
96bool VerifySpecificPathControlledByUser(const FilePath& path,
97 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +090098 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +090099 stat_wrapper_t stat_info;
100 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900101 DPLOG(ERROR) << "Failed to get information on path "
102 << path.value();
skerner@google.com93449ef2011-09-22 23:47:18 +0900103 return false;
104 }
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900105
skerner@google.com93449ef2011-09-22 23:47:18 +0900106 if (S_ISLNK(stat_info.st_mode)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900107 DLOG(ERROR) << "Path " << path.value()
skerner@google.com93449ef2011-09-22 23:47:18 +0900108 << " is a symbolic link.";
109 return false;
110 }
111
112 if (stat_info.st_uid != owner_uid) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900113 DLOG(ERROR) << "Path " << path.value()
114 << " is owned by the wrong user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900115 return false;
116 }
117
skerner@chromium.org80784142011-10-18 06:30:29 +0900118 if ((stat_info.st_mode & S_IWGRP) &&
119 !ContainsKey(group_gids, stat_info.st_gid)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900120 DLOG(ERROR) << "Path " << path.value()
121 << " is writable by an unprivileged group.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900122 return false;
123 }
124
125 if (stat_info.st_mode & S_IWOTH) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900126 DLOG(ERROR) << "Path " << path.value()
127 << " is writable by any user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900128 return false;
129 }
130
131 return true;
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900132}
skerner@google.com93449ef2011-09-22 23:47:18 +0900133
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900134std::string TempFileName() {
135#if defined(OS_MACOSX)
136 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
137#endif
138
139#if defined(GOOGLE_CHROME_BUILD)
140 return std::string(".com.google.Chrome.XXXXXX");
141#else
142 return std::string(".org.chromium.Chromium.XXXXXX");
143#endif
144}
145
skerner@google.com93449ef2011-09-22 23:47:18 +0900146} // namespace
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900147
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900148FilePath MakeAbsoluteFilePath(const FilePath& input) {
149 ThreadRestrictions::AssertIOAllowed();
150 char full_path[PATH_MAX];
151 if (realpath(input.value().c_str(), full_path) == NULL)
152 return FilePath();
153 return FilePath(full_path);
mark@chromium.org13aa8aa2011-04-22 13:15:13 +0900154}
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900155
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900156// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
157// which works both with and without the recursive flag. I'm not sure we need
158// that functionality. If not, remove from file_util_win.cc, otherwise add it
159// here.
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900160bool DeleteFile(const FilePath& path, bool recursive) {
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900161 ThreadRestrictions::AssertIOAllowed();
evanm@google.com874d1672008-10-31 08:54:04 +0900162 const char* path_str = path.value().c_str();
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900163 stat_wrapper_t file_info;
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900164 int test = CallLstat(path_str, &file_info);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900165 if (test != 0) {
166 // The Windows version defines this condition as success.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900167 bool ret = (errno == ENOENT || errno == ENOTDIR);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900168 return ret;
169 }
170 if (!S_ISDIR(file_info.st_mode))
evanm@google.com874d1672008-10-31 08:54:04 +0900171 return (unlink(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900172 if (!recursive)
evanm@google.com874d1672008-10-31 08:54:04 +0900173 return (rmdir(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900174
175 bool success = true;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900176 std::stack<std::string> directories;
177 directories.push(path.value());
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900178 FileEnumerator traversal(path, true,
179 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
180 FileEnumerator::SHOW_SYM_LINKS);
thestig@chromium.org3217c822009-08-07 06:23:07 +0900181 for (FilePath current = traversal.Next(); success && !current.empty();
182 current = traversal.Next()) {
brettw@chromium.org56946722013-06-08 13:53:36 +0900183 if (traversal.GetInfo().IsDirectory())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900184 directories.push(current.value());
185 else
186 success = (unlink(current.value().c_str()) == 0);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900187 }
thestig@chromium.org3217c822009-08-07 06:23:07 +0900188
189 while (success && !directories.empty()) {
190 FilePath dir = FilePath(directories.top());
191 directories.pop();
192 success = (rmdir(dir.value().c_str()) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900193 }
194 return success;
195}
196
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900197bool ReplaceFile(const FilePath& from_path,
198 const FilePath& to_path,
199 PlatformFileError* error) {
200 ThreadRestrictions::AssertIOAllowed();
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900201 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
202 return true;
203 if (error)
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900204 *error = ErrnoToPlatformFileError(errno);
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900205 return false;
phajdan.jr@chromium.orgd86bea02009-05-20 02:21:07 +0900206}
207
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900208bool CopyDirectory(const FilePath& from_path,
209 const FilePath& to_path,
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900210 bool recursive) {
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900211 ThreadRestrictions::AssertIOAllowed();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900212 // Some old callers of CopyDirectory want it to support wildcards.
213 // After some discussion, we decided to fix those callers.
214 // Break loudly here if anyone tries to do this.
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900215 // TODO(evanm): remove this once we're sure it's ok.
evanm@google.com874d1672008-10-31 08:54:04 +0900216 DCHECK(to_path.value().find('*') == std::string::npos);
217 DCHECK(from_path.value().find('*') == std::string::npos);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900218
219 char top_dir[PATH_MAX];
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900220 if (strlcpy(top_dir, from_path.value().c_str(),
221 arraysize(top_dir)) >= arraysize(top_dir)) {
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900222 return false;
223 }
224
thestig@chromium.org3217c822009-08-07 06:23:07 +0900225 // This function does not properly handle destinations within the source
226 FilePath real_to_path = to_path;
brettw@chromium.org10b64122013-07-12 02:36:07 +0900227 if (PathExists(real_to_path)) {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900228 real_to_path = MakeAbsoluteFilePath(real_to_path);
229 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900230 return false;
231 } else {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900232 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
233 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900234 return false;
235 }
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900236 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
237 if (real_from_path.empty())
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900238 return false;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900239 if (real_to_path.value().size() >= real_from_path.value().size() &&
240 real_to_path.value().compare(0, real_from_path.value().size(),
241 real_from_path.value()) == 0)
242 return false;
243
244 bool success = true;
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900245 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900246 if (recursive)
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900247 traverse_type |= FileEnumerator::DIRECTORIES;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900248 FileEnumerator traversal(from_path, recursive, traverse_type);
249
vandebo@chromium.org70cf3f12009-10-14 02:57:27 +0900250 // We have to mimic windows behavior here. |to_path| may not exist yet,
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900251 // start the loop with |to_path|.
brettw@chromium.org56946722013-06-08 13:53:36 +0900252 struct stat from_stat;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900253 FilePath current = from_path;
brettw@chromium.org56946722013-06-08 13:53:36 +0900254 if (stat(from_path.value().c_str(), &from_stat) < 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900255 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
256 << from_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900257 success = false;
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900258 }
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900259 struct stat to_path_stat;
260 FilePath from_path_base = from_path;
261 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
262 S_ISDIR(to_path_stat.st_mode)) {
263 // If the destination already exists and is a directory, then the
264 // top level of source needs to be copied.
265 from_path_base = from_path.DirName();
266 }
267
268 // The Windows version of this function assumes that non-recursive calls
269 // will always have a directory for from_path.
brettw@chromium.org56946722013-06-08 13:53:36 +0900270 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900271
thestig@chromium.org3217c822009-08-07 06:23:07 +0900272 while (success && !current.empty()) {
aedla@chromium.orgfef1a202013-01-30 20:38:02 +0900273 // current is the source path, including from_path, so append
274 // the suffix after from_path to to_path to create the target_path.
275 FilePath target_path(to_path);
276 if (from_path_base != current) {
277 if (!from_path_base.AppendRelativePath(current, &target_path)) {
278 success = false;
279 break;
280 }
phajdan.jr@chromium.orgecf50752009-01-14 03:57:46 +0900281 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900282
brettw@chromium.org56946722013-06-08 13:53:36 +0900283 if (S_ISDIR(from_stat.st_mode)) {
284 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
thestig@chromium.org3217c822009-08-07 06:23:07 +0900285 errno != EEXIST) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900286 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
287 << target_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900288 success = false;
289 }
brettw@chromium.org56946722013-06-08 13:53:36 +0900290 } else if (S_ISREG(from_stat.st_mode)) {
thestig@chromium.org3217c822009-08-07 06:23:07 +0900291 if (!CopyFile(current, target_path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900292 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
293 << target_path.value();
thestig@chromium.org3217c822009-08-07 06:23:07 +0900294 success = false;
295 }
296 } else {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900297 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
298 << current.value();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900299 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900300
thestig@chromium.org3217c822009-08-07 06:23:07 +0900301 current = traversal.Next();
brettw@chromium.org56946722013-06-08 13:53:36 +0900302 if (!current.empty())
303 from_stat = traversal.GetInfo().stat();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900304 }
305
thestig@chromium.org3217c822009-08-07 06:23:07 +0900306 return success;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900307}
308
brettw@chromium.org10b64122013-07-12 02:36:07 +0900309bool PathExists(const FilePath& path) {
310 ThreadRestrictions::AssertIOAllowed();
311 return access(path.value().c_str(), F_OK) == 0;
312}
313
brettw@chromium.org5a112e72013-07-16 05:18:09 +0900314bool PathIsWritable(const FilePath& path) {
315 ThreadRestrictions::AssertIOAllowed();
316 return access(path.value().c_str(), W_OK) == 0;
317}
318
319bool DirectoryExists(const FilePath& path) {
320 ThreadRestrictions::AssertIOAllowed();
321 stat_wrapper_t file_info;
322 if (CallStat(path.value().c_str(), &file_info) == 0)
323 return S_ISDIR(file_info.st_mode);
324 return false;
325}
326
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900327} // namespace base
328
329// -----------------------------------------------------------------------------
330
331namespace file_util {
332
333using base::stat_wrapper_t;
334using base::CallStat;
335using base::CallLstat;
brettw@chromium.org5a112e72013-07-16 05:18:09 +0900336using base::DirectoryExists;
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900337using base::FileEnumerator;
338using base::FilePath;
339using base::MakeAbsoluteFilePath;
340using base::RealPath;
341using base::VerifySpecificPathControlledByUser;
342
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900343bool ReadFromFD(int fd, char* buffer, size_t bytes) {
344 size_t total_read = 0;
345 while (total_read < bytes) {
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900346 ssize_t bytes_read =
347 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
348 if (bytes_read <= 0)
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900349 break;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900350 total_read += bytes_read;
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900351 }
352 return total_read == bytes;
353}
354
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900355bool CreateSymbolicLink(const FilePath& target_path,
356 const FilePath& symlink_path) {
357 DCHECK(!symlink_path.empty());
358 DCHECK(!target_path.empty());
359 return ::symlink(target_path.value().c_str(),
360 symlink_path.value().c_str()) != -1;
361}
362
363bool ReadSymbolicLink(const FilePath& symlink_path,
364 FilePath* target_path) {
365 DCHECK(!symlink_path.empty());
366 DCHECK(target_path);
367 char buf[PATH_MAX];
368 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
369
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900370 if (count <= 0) {
371 target_path->clear();
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900372 return false;
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900373 }
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900374
375 *target_path = FilePath(FilePath::StringType(buf, count));
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900376 return true;
377}
378
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900379bool GetPosixFilePermissions(const FilePath& path, int* mode) {
380 base::ThreadRestrictions::AssertIOAllowed();
381 DCHECK(mode);
382
383 stat_wrapper_t file_info;
384 // Uses stat(), because on symbolic link, lstat() does not return valid
385 // permission bits in st_mode
386 if (CallStat(path.value().c_str(), &file_info) != 0)
387 return false;
388
389 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
390 return true;
391}
392
393bool SetPosixFilePermissions(const FilePath& path,
394 int mode) {
395 base::ThreadRestrictions::AssertIOAllowed();
396 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
397
398 // Calls stat() so that we can preserve the higher bits like S_ISGID.
399 stat_wrapper_t stat_buf;
400 if (CallStat(path.value().c_str(), &stat_buf) != 0)
401 return false;
402
403 // Clears the existing permission bits, and adds the new ones.
404 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
405 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
406
407 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
408 return false;
409
410 return true;
411}
412
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900413// Creates and opens a temporary file in |directory|, returning the
erikkay@chromium.org3a9a6422009-09-12 02:33:50 +0900414// file descriptor. |path| is set to the temporary file path.
415// This function does NOT unlink() the file.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900416int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900417 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900418 *path = directory.Append(base::TempFileName());
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900419 const std::string& tmpdir_string = path->value();
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900420 // this should be OK since mkstemp just replaces characters in place
421 char* buffer = const_cast<char*>(tmpdir_string.c_str());
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900422
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900423 return HANDLE_EINTR(mkstemp(buffer));
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900424}
425
erikkay@chromium.org18f0dde2009-08-19 01:07:55 +0900426bool CreateTemporaryFile(FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900427 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900428 FilePath directory;
429 if (!GetTempDir(&directory))
430 return false;
431 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900432 if (fd < 0)
433 return false;
phajdan.jr@chromium.orgcad925c2011-04-12 15:51:22 +0900434 ignore_result(HANDLE_EINTR(close(fd)));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900435 return true;
436}
437
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900438FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900439 FilePath directory;
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900440 if (!GetShmemTempDir(&directory, executable))
evan@chromium.org2abe0b42010-06-11 07:56:23 +0900441 return NULL;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900442
phajdan.jr@chromium.org8139fe12009-04-28 15:50:36 +0900443 return CreateAndOpenTemporaryFileInDir(directory, path);
444}
445
446FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
447 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900448 if (fd < 0)
449 return NULL;
450
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900451 FILE* file = fdopen(fd, "a+");
452 if (!file)
453 ignore_result(HANDLE_EINTR(close(fd)));
454 return file;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900455}
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900456
457bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900458 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900459 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900460 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
jcampan@chromium.orgbf29e602008-10-11 03:50:32 +0900461}
462
skerner@chromium.orge4432392010-05-01 02:00:09 +0900463static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
464 const FilePath::StringType& name_tmpl,
465 FilePath* new_dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900466 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900467 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
468 << "Directory name template must contain \"XXXXXX\".";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900469
470 FilePath sub_dir = base_dir.Append(name_tmpl);
471 std::string sub_dir_string = sub_dir.value();
472
473 // this should be OK since mkdtemp just replaces characters in place
474 char* buffer = const_cast<char*>(sub_dir_string.c_str());
475 char* dtemp = mkdtemp(buffer);
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900476 if (!dtemp) {
477 DPLOG(ERROR) << "mkdtemp";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900478 return false;
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900479 }
skerner@chromium.orge4432392010-05-01 02:00:09 +0900480 *new_dir = FilePath(dtemp);
481 return true;
482}
483
484bool CreateTemporaryDirInDir(const FilePath& base_dir,
485 const FilePath::StringType& prefix,
skerner@chromium.orgbd112ab2010-06-30 16:19:11 +0900486 FilePath* new_dir) {
skerner@chromium.orge4432392010-05-01 02:00:09 +0900487 FilePath::StringType mkdtemp_template = prefix;
488 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
489 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
490}
491
erikkay@google.comcce83822008-12-24 05:20:10 +0900492bool CreateNewTempDirectory(const FilePath::StringType& prefix,
493 FilePath* new_temp_path) {
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900494 FilePath tmpdir;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900495 if (!GetTempDir(&tmpdir))
496 return false;
skerner@chromium.orge4432392010-05-01 02:00:09 +0900497
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900498 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
499 new_temp_path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900500}
501
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900502bool CreateDirectoryAndGetError(const FilePath& full_path,
503 base::PlatformFileError* error) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900504 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
evanm@google.com874d1672008-10-31 08:54:04 +0900505 std::vector<FilePath> subpaths;
506
507 // Collect a list of all parent directories.
508 FilePath last_path = full_path;
509 subpaths.push_back(full_path);
510 for (FilePath path = full_path.DirName();
511 path.value() != last_path.value(); path = path.DirName()) {
512 subpaths.push_back(path);
513 last_path = path;
514 }
515
516 // Iterate through the parents and create the missing ones.
517 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
518 i != subpaths.rend(); ++i) {
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900519 if (DirectoryExists(*i))
520 continue;
521 if (mkdir(i->value().c_str(), 0700) == 0)
522 continue;
523 // Mkdir failed, but it might have failed with EEXIST, or some other error
524 // due to the the directory appearing out of thin air. This can occur if
525 // two processes are trying to create the same file system tree at the same
526 // time. Check to see if it exists and make sure it is a directory.
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900527 int saved_errno = errno;
528 if (!DirectoryExists(*i)) {
529 if (error)
530 *error = base::ErrnoToPlatformFileError(saved_errno);
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900531 return false;
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900532 }
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900533 }
534 return true;
535}
536
jeremya@chromium.org05609662013-04-04 18:05:21 +0900537base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
538 const int kMaxAttempts = 20;
539 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
dcheng@chromium.org8164c2c2013-04-09 17:46:45 +0900540 int uniquifier =
541 GetUniquePathNumber(path, base::FilePath::StringType());
jeremya@chromium.org05609662013-04-04 18:05:21 +0900542 if (uniquifier < 0)
543 break;
544 base::FilePath test_path = (uniquifier == 0) ? path :
545 path.InsertBeforeExtensionASCII(
546 base::StringPrintf(" (%d)", uniquifier));
547 if (mkdir(test_path.value().c_str(), 0777) == 0)
548 return test_path;
549 else if (errno != EEXIST)
550 break;
551 }
552 return base::FilePath();
553}
554
rkc@chromium.orga40af282011-06-01 08:10:06 +0900555// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
556// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
557bool IsLink(const FilePath& file_path) {
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900558 stat_wrapper_t st;
rkc@chromium.orga40af282011-06-01 08:10:06 +0900559 // If we can't lstat the file, it's safe to assume that the file won't at
560 // least be a 'followable' link.
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900561 if (CallLstat(file_path.value().c_str(), &st) != 0)
rkc@chromium.orga40af282011-06-01 08:10:06 +0900562 return false;
563
564 if (S_ISLNK(st.st_mode))
565 return true;
566 else
567 return false;
568}
569
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900570bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900571 stat_wrapper_t file_info;
qinmin@chromium.org94f7f262013-11-19 03:10:58 +0900572 if (CallStat(file_path.value().c_str(), &file_info) != 0)
573 return false;
darin@google.com7f479f22008-09-26 10:04:08 +0900574 results->is_directory = S_ISDIR(file_info.st_mode);
575 results->size = file_info.st_size;
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900576#if defined(OS_MACOSX)
577 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
578 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
579 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
580#elif defined(OS_ANDROID)
brettw@chromium.orgdbc9b5a2009-07-25 01:13:53 +0900581 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900582 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
583 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900584#else
585 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
586 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
587 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
588#endif
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900589 return true;
590}
591
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900592bool GetInode(const FilePath& path, ino_t* inode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900593 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900594 struct stat buffer;
595 int result = stat(path.value().c_str(), &buffer);
596 if (result < 0)
597 return false;
598
599 *inode = buffer.st_ino;
600 return true;
601}
602
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900603FILE* OpenFile(const std::string& filename, const char* mode) {
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900604 return OpenFile(FilePath(filename), mode);
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900605}
606
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900607FILE* OpenFile(const FilePath& filename, const char* mode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900608 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900609 FILE* result = NULL;
610 do {
611 result = fopen(filename.value().c_str(), mode);
612 } while (!result && errno == EINTR);
613 return result;
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900614}
615
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900616int ReadFile(const FilePath& filename, char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900617 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900618 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900619 if (fd < 0)
620 return -1;
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900621
evan@chromium.org36699862010-02-02 11:28:16 +0900622 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
623 if (int ret = HANDLE_EINTR(close(fd)) < 0)
624 return ret;
625 return bytes_read;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900626}
627
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900628int WriteFile(const FilePath& filename, const char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900629 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900630 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900631 if (fd < 0)
632 return -1;
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900633
evan@chromium.org36699862010-02-02 11:28:16 +0900634 int bytes_written = WriteFileDescriptor(fd, data, size);
635 if (int ret = HANDLE_EINTR(close(fd)) < 0)
636 return ret;
637 return bytes_written;
estade@chromium.org557da512009-09-16 09:29:22 +0900638}
639
640int WriteFileDescriptor(const int fd, const char* data, int size) {
641 // Allow for partial writes.
642 ssize_t bytes_written_total = 0;
643 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
644 bytes_written_total += bytes_written_partial) {
645 bytes_written_partial =
646 HANDLE_EINTR(write(fd, data + bytes_written_total,
647 size - bytes_written_total));
648 if (bytes_written_partial < 0)
649 return -1;
650 }
651
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900652 return bytes_written_total;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900653}
654
loislo@chromium.orgeae0dcb2012-04-29 21:57:10 +0900655int AppendToFile(const FilePath& filename, const char* data, int size) {
656 base::ThreadRestrictions::AssertIOAllowed();
657 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
658 if (fd < 0)
659 return -1;
660
661 int bytes_written = WriteFileDescriptor(fd, data, size);
662 if (int ret = HANDLE_EINTR(close(fd)) < 0)
663 return ret;
664 return bytes_written;
665}
666
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900667// Gets the current working directory for the process.
evanm@google.com874d1672008-10-31 08:54:04 +0900668bool GetCurrentDirectory(FilePath* dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900669 // getcwd can return ENOENT, which implies it checks against the disk.
670 base::ThreadRestrictions::AssertIOAllowed();
671
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900672 char system_buffer[PATH_MAX] = "";
evanm@google.com874d1672008-10-31 08:54:04 +0900673 if (!getcwd(system_buffer, sizeof(system_buffer))) {
674 NOTREACHED();
675 return false;
676 }
677 *dir = FilePath(system_buffer);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900678 return true;
679}
680
681// Sets the current working directory for the process.
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900682bool SetCurrentDirectory(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900683 base::ThreadRestrictions::AssertIOAllowed();
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900684 int ret = chdir(path.value().c_str());
685 return !ret;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900686}
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900687
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900688bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
689 FilePath real_path_result;
690 if (!RealPath(path, &real_path_result))
skerner@chromium.org559baa92010-05-13 00:13:57 +0900691 return false;
692
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900693 // To be consistant with windows, fail if |real_path_result| is a
694 // directory.
695 stat_wrapper_t file_info;
696 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
697 S_ISDIR(file_info.st_mode))
698 return false;
699
700 *normalized_path = real_path_result;
skerner@chromium.org559baa92010-05-13 00:13:57 +0900701 return true;
702}
703
evan@chromium.orgb9575332010-04-22 06:11:36 +0900704#if !defined(OS_MACOSX)
705bool GetTempDir(FilePath* path) {
706 const char* tmp = getenv("TMPDIR");
707 if (tmp)
708 *path = FilePath(tmp);
709 else
michaelbai@google.com2251c622011-06-22 07:34:50 +0900710#if defined(OS_ANDROID)
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +0900711 return PathService::Get(base::DIR_CACHE, path);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900712#else
evan@chromium.orgb9575332010-04-22 06:11:36 +0900713 *path = FilePath("/tmp");
michaelbai@google.com2251c622011-06-22 07:34:50 +0900714#endif
evan@chromium.orgb9575332010-04-22 06:11:36 +0900715 return true;
716}
717
michaelbai@google.com2251c622011-06-22 07:34:50 +0900718#if !defined(OS_ANDROID)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900719
robert.nagy@gmail.comea54e462011-10-25 07:05:27 +0900720#if defined(OS_LINUX)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900721// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
722// This depends on the mount options used for /dev/shm, which vary among
723// different Linux distributions and possibly local configuration. It also
724// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
725// but its kernel allows mprotect with PROT_EXEC anyway.
726
727namespace {
728
729bool DetermineDevShmExecutable() {
730 bool result = false;
731 FilePath path;
732 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
733 if (fd >= 0) {
734 ScopedFD shm_fd_closer(&fd);
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900735 DeleteFile(path, false);
scr@chromium.orge7506992011-12-23 07:31:44 +0900736 long sysconf_result = sysconf(_SC_PAGESIZE);
737 CHECK_GE(sysconf_result, 0);
738 size_t pagesize = static_cast<size_t>(sysconf_result);
739 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900740 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
741 if (mapping != MAP_FAILED) {
742 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
743 result = true;
744 munmap(mapping, pagesize);
745 }
746 }
747 return result;
evan@chromium.orgb9575332010-04-22 06:11:36 +0900748}
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900749
750}; // namespace
751#endif // defined(OS_LINUX)
752
753bool GetShmemTempDir(FilePath* path, bool executable) {
754#if defined(OS_LINUX)
755 bool use_dev_shm = true;
756 if (executable) {
757 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
758 use_dev_shm = s_dev_shm_executable;
759 }
760 if (use_dev_shm) {
761 *path = FilePath("/dev/shm");
762 return true;
763 }
michaelbai@google.com2251c622011-06-22 07:34:50 +0900764#endif
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900765 return GetTempDir(path);
766}
767#endif // !defined(OS_ANDROID)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900768
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900769FilePath GetHomeDir() {
haruki@chromium.org712ff262012-08-06 18:14:44 +0900770#if defined(OS_CHROMEOS)
stevenjb@chromium.org861313b2013-09-28 04:28:24 +0900771 if (base::SysInfo::IsRunningOnChromeOS())
haruki@chromium.org712ff262012-08-06 18:14:44 +0900772 return FilePath("/home/chronos/user");
773#endif
774
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900775 const char* home_dir = getenv("HOME");
776 if (home_dir && home_dir[0])
777 return FilePath(home_dir);
778
michaelbai@google.com2251c622011-06-22 07:34:50 +0900779#if defined(OS_ANDROID)
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900780 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
spang@chromium.org8d0fa9a2013-11-20 14:33:46 +0900781#elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900782 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
783 base::ThreadRestrictions::AssertIOAllowed();
784
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900785 home_dir = g_get_home_dir();
786 if (home_dir && home_dir[0])
787 return FilePath(home_dir);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900788#endif
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900789
790 FilePath rv;
791 if (file_util::GetTempDir(&rv))
792 return rv;
793
794 // Last resort.
795 return FilePath("/tmp");
796}
thorogood@chromium.orge77009d2012-07-23 17:22:44 +0900797#endif // !defined(OS_MACOSX)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900798
skerner@google.com93449ef2011-09-22 23:47:18 +0900799bool VerifyPathControlledByUser(const FilePath& base,
800 const FilePath& path,
801 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900802 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900803 if (base != path && !base.IsParent(path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900804 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
805 << base.value() << "\", path = \"" << path.value() << "\"";
skerner@google.com93449ef2011-09-22 23:47:18 +0900806 return false;
807 }
808
809 std::vector<FilePath::StringType> base_components;
810 std::vector<FilePath::StringType> path_components;
811
812 base.GetComponents(&base_components);
813 path.GetComponents(&path_components);
814
815 std::vector<FilePath::StringType>::const_iterator ib, ip;
816 for (ib = base_components.begin(), ip = path_components.begin();
817 ib != base_components.end(); ++ib, ++ip) {
818 // |base| must be a subpath of |path|, so all components should match.
819 // If these CHECKs fail, look at the test that base is a parent of
820 // path at the top of this function.
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900821 DCHECK(ip != path_components.end());
822 DCHECK(*ip == *ib);
skerner@google.com93449ef2011-09-22 23:47:18 +0900823 }
824
825 FilePath current_path = base;
skerner@chromium.org80784142011-10-18 06:30:29 +0900826 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900827 return false;
828
829 for (; ip != path_components.end(); ++ip) {
830 current_path = current_path.Append(*ip);
skerner@chromium.org80784142011-10-18 06:30:29 +0900831 if (!VerifySpecificPathControlledByUser(
832 current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900833 return false;
834 }
835 return true;
836}
837
qsr@chromium.org4ab5de92012-07-09 23:40:39 +0900838#if defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900839bool VerifyPathControlledByAdmin(const FilePath& path) {
840 const unsigned kRootUid = 0;
841 const FilePath kFileSystemRoot("/");
842
843 // The name of the administrator group on mac os.
skerner@chromium.org80784142011-10-18 06:30:29 +0900844 const char* const kAdminGroupNames[] = {
845 "admin",
846 "wheel"
847 };
skerner@google.com93449ef2011-09-22 23:47:18 +0900848
849 // Reading the groups database may touch the file system.
850 base::ThreadRestrictions::AssertIOAllowed();
851
skerner@chromium.org80784142011-10-18 06:30:29 +0900852 std::set<gid_t> allowed_group_ids;
853 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
854 struct group *group_record = getgrnam(kAdminGroupNames[i]);
855 if (!group_record) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900856 DPLOG(ERROR) << "Could not get the group ID of group \""
857 << kAdminGroupNames[i] << "\".";
skerner@chromium.org80784142011-10-18 06:30:29 +0900858 continue;
859 }
860
861 allowed_group_ids.insert(group_record->gr_gid);
skerner@google.com93449ef2011-09-22 23:47:18 +0900862 }
863
864 return VerifyPathControlledByUser(
skerner@chromium.org80784142011-10-18 06:30:29 +0900865 kFileSystemRoot, path, kRootUid, allowed_group_ids);
skerner@google.com93449ef2011-09-22 23:47:18 +0900866}
stuartmorgan@chromium.org925e0b72012-07-24 20:23:32 +0900867#endif // defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900868
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900869int GetMaximumPathComponentLength(const FilePath& path) {
870 base::ThreadRestrictions::AssertIOAllowed();
871 return pathconf(path.value().c_str(), _PC_NAME_MAX);
872}
873
thestig@chromium.org7ecbbc12010-11-20 12:38:15 +0900874} // namespace file_util
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900875
876namespace base {
877namespace internal {
878
879bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
880 ThreadRestrictions::AssertIOAllowed();
881 // Windows compatibility: if to_path exists, from_path and to_path
882 // must be the same type, either both files, or both directories.
883 stat_wrapper_t to_file_info;
884 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
885 stat_wrapper_t from_file_info;
886 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
887 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
888 return false;
889 } else {
890 return false;
891 }
892 }
893
894 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
895 return true;
896
897 if (!CopyDirectory(from_path, to_path, true))
898 return false;
899
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900900 DeleteFile(from_path, true);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900901 return true;
902}
903
904#if !defined(OS_MACOSX)
905// Mac has its own implementation, this is for all other Posix systems.
906bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
907 ThreadRestrictions::AssertIOAllowed();
908 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
909 if (infile < 0)
910 return false;
911
912 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
913 if (outfile < 0) {
914 ignore_result(HANDLE_EINTR(close(infile)));
915 return false;
916 }
917
918 const size_t kBufferSize = 32768;
919 std::vector<char> buffer(kBufferSize);
920 bool result = true;
921
922 while (result) {
923 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
924 if (bytes_read < 0) {
925 result = false;
926 break;
927 }
928 if (bytes_read == 0)
929 break;
930 // Allow for partial writes
931 ssize_t bytes_written_per_read = 0;
932 do {
933 ssize_t bytes_written_partial = HANDLE_EINTR(write(
934 outfile,
935 &buffer[bytes_written_per_read],
936 bytes_read - bytes_written_per_read));
937 if (bytes_written_partial < 0) {
938 result = false;
939 break;
940 }
941 bytes_written_per_read += bytes_written_partial;
942 } while (bytes_written_per_read < bytes_read);
943 }
944
945 if (HANDLE_EINTR(close(infile)) < 0)
946 result = false;
947 if (HANDLE_EINTR(close(outfile)) < 0)
948 result = false;
949
950 return result;
951}
952#endif // !defined(OS_MACOSX)
953
954} // namespace internal
955} // namespace base