blob: 03afea7214cf9f2e799bcca7f16730625bf7cc32 [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"
brettw@chromium.orgb52f29b2014-03-18 04:02:35 +090036#include "base/files/scoped_file.h"
mmentovai@google.comaa13be62008-09-03 03:20:34 +090037#include "base/logging.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090038#include "base/memory/scoped_ptr.h"
39#include "base/memory/singleton.h"
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +090040#include "base/path_service.h"
brettw@chromium.orgb1788fb2012-11-15 05:54:35 +090041#include "base/posix/eintr_wrapper.h"
skerner@chromium.org80784142011-10-18 06:30:29 +090042#include "base/stl_util.h"
avi@chromium.org94bd5732013-06-11 22:36:37 +090043#include "base/strings/string_util.h"
44#include "base/strings/stringprintf.h"
brettw@chromium.org1f67a912013-02-08 04:18:03 +090045#include "base/strings/sys_string_conversions.h"
avi@chromium.org17f60622013-06-08 03:37:07 +090046#include "base/strings/utf_string_conversions.h"
stevenjb@chromium.org861313b2013-09-28 04:28:24 +090047#include "base/sys_info.h"
brettw@chromium.org5b5f5e02011-01-01 10:01:06 +090048#include "base/threading/thread_restrictions.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090049#include "base/time/time.h"
estade@chromium.org868ecbc2009-06-24 12:29:26 +090050
michaelbai@google.com2251c622011-06-22 07:34:50 +090051#if defined(OS_ANDROID)
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +090052#include "base/android/content_uri_utils.h"
michaelbai@google.com2251c622011-06-22 07:34:50 +090053#include "base/os_compat_android.h"
54#endif
55
qsr@chromium.org4ab5de92012-07-09 23:40:39 +090056#if !defined(OS_IOS)
57#include <grp.h>
58#endif
59
brettw@chromium.org99b198e2013-04-12 14:17:15 +090060namespace base {
61
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090062namespace {
63
rsesek@chromium.orgdc818ac2012-07-20 07:24:02 +090064#if defined(OS_BSD) || defined(OS_MACOSX)
skerner@google.com93449ef2011-09-22 23:47:18 +090065typedef struct stat stat_wrapper_t;
66static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090067 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090068 return stat(path, sb);
69}
70static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090071 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090072 return lstat(path, sb);
73}
rvargas@chromium.org799ba6c2014-03-21 09:41:15 +090074#else // defined(OS_BSD) || defined(OS_MACOSX)
skerner@google.com93449ef2011-09-22 23:47:18 +090075typedef struct stat64 stat_wrapper_t;
76static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090077 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090078 return stat64(path, sb);
79}
80static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090081 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090082 return lstat64(path, sb);
83}
rvargas@chromium.org799ba6c2014-03-21 09:41:15 +090084#endif // !(defined(OS_BSD) || defined(OS_MACOSX))
skerner@google.com93449ef2011-09-22 23:47:18 +090085
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090086// Helper for NormalizeFilePath(), defined below.
87bool RealPath(const FilePath& path, FilePath* real_path) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090088 ThreadRestrictions::AssertIOAllowed(); // For realpath().
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090089 FilePath::CharType buf[PATH_MAX];
90 if (!realpath(path.value().c_str(), buf))
91 return false;
92
93 *real_path = FilePath(buf);
94 return true;
95}
96
skerner@google.com93449ef2011-09-22 23:47:18 +090097// Helper for VerifyPathControlledByUser.
98bool VerifySpecificPathControlledByUser(const FilePath& path,
99 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900100 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900101 stat_wrapper_t stat_info;
102 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900103 DPLOG(ERROR) << "Failed to get information on path "
104 << path.value();
skerner@google.com93449ef2011-09-22 23:47:18 +0900105 return false;
106 }
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900107
skerner@google.com93449ef2011-09-22 23:47:18 +0900108 if (S_ISLNK(stat_info.st_mode)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900109 DLOG(ERROR) << "Path " << path.value()
skerner@google.com93449ef2011-09-22 23:47:18 +0900110 << " is a symbolic link.";
111 return false;
112 }
113
114 if (stat_info.st_uid != owner_uid) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900115 DLOG(ERROR) << "Path " << path.value()
116 << " is owned by the wrong user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900117 return false;
118 }
119
skerner@chromium.org80784142011-10-18 06:30:29 +0900120 if ((stat_info.st_mode & S_IWGRP) &&
121 !ContainsKey(group_gids, stat_info.st_gid)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900122 DLOG(ERROR) << "Path " << path.value()
123 << " is writable by an unprivileged group.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900124 return false;
125 }
126
127 if (stat_info.st_mode & S_IWOTH) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900128 DLOG(ERROR) << "Path " << path.value()
129 << " is writable by any user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900130 return false;
131 }
132
133 return true;
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900134}
skerner@google.com93449ef2011-09-22 23:47:18 +0900135
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900136std::string TempFileName() {
137#if defined(OS_MACOSX)
138 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
139#endif
140
141#if defined(GOOGLE_CHROME_BUILD)
142 return std::string(".com.google.Chrome.XXXXXX");
143#else
144 return std::string(".org.chromium.Chromium.XXXXXX");
145#endif
146}
147
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900148// Creates and opens a temporary file in |directory|, returning the
149// file descriptor. |path| is set to the temporary file path.
150// This function does NOT unlink() the file.
151int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
152 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
153 *path = directory.Append(base::TempFileName());
154 const std::string& tmpdir_string = path->value();
155 // this should be OK since mkstemp just replaces characters in place
156 char* buffer = const_cast<char*>(tmpdir_string.c_str());
157
158 return HANDLE_EINTR(mkstemp(buffer));
159}
160
161#if defined(OS_LINUX)
162// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
163// This depends on the mount options used for /dev/shm, which vary among
164// different Linux distributions and possibly local configuration. It also
165// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
166// but its kernel allows mprotect with PROT_EXEC anyway.
167bool DetermineDevShmExecutable() {
168 bool result = false;
169 FilePath path;
brettw@chromium.orgb52f29b2014-03-18 04:02:35 +0900170
171 ScopedFD fd(CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path));
172 if (fd.is_valid()) {
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900173 DeleteFile(path, false);
174 long sysconf_result = sysconf(_SC_PAGESIZE);
175 CHECK_GE(sysconf_result, 0);
176 size_t pagesize = static_cast<size_t>(sysconf_result);
177 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
brettw@chromium.orgb52f29b2014-03-18 04:02:35 +0900178 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd.get(), 0);
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900179 if (mapping != MAP_FAILED) {
180 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
181 result = true;
182 munmap(mapping, pagesize);
183 }
184 }
185 return result;
186}
187#endif // defined(OS_LINUX)
188
skerner@google.com93449ef2011-09-22 23:47:18 +0900189} // namespace
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900190
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900191FilePath MakeAbsoluteFilePath(const FilePath& input) {
192 ThreadRestrictions::AssertIOAllowed();
193 char full_path[PATH_MAX];
194 if (realpath(input.value().c_str(), full_path) == NULL)
195 return FilePath();
196 return FilePath(full_path);
mark@chromium.org13aa8aa2011-04-22 13:15:13 +0900197}
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900198
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900199// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
200// which works both with and without the recursive flag. I'm not sure we need
201// that functionality. If not, remove from file_util_win.cc, otherwise add it
202// here.
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900203bool DeleteFile(const FilePath& path, bool recursive) {
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900204 ThreadRestrictions::AssertIOAllowed();
evanm@google.com874d1672008-10-31 08:54:04 +0900205 const char* path_str = path.value().c_str();
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900206 stat_wrapper_t file_info;
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900207 int test = CallLstat(path_str, &file_info);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900208 if (test != 0) {
209 // The Windows version defines this condition as success.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900210 bool ret = (errno == ENOENT || errno == ENOTDIR);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900211 return ret;
212 }
213 if (!S_ISDIR(file_info.st_mode))
evanm@google.com874d1672008-10-31 08:54:04 +0900214 return (unlink(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900215 if (!recursive)
evanm@google.com874d1672008-10-31 08:54:04 +0900216 return (rmdir(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900217
218 bool success = true;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900219 std::stack<std::string> directories;
220 directories.push(path.value());
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900221 FileEnumerator traversal(path, true,
222 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
223 FileEnumerator::SHOW_SYM_LINKS);
thestig@chromium.org3217c822009-08-07 06:23:07 +0900224 for (FilePath current = traversal.Next(); success && !current.empty();
225 current = traversal.Next()) {
brettw@chromium.org56946722013-06-08 13:53:36 +0900226 if (traversal.GetInfo().IsDirectory())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900227 directories.push(current.value());
228 else
229 success = (unlink(current.value().c_str()) == 0);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900230 }
thestig@chromium.org3217c822009-08-07 06:23:07 +0900231
232 while (success && !directories.empty()) {
233 FilePath dir = FilePath(directories.top());
234 directories.pop();
235 success = (rmdir(dir.value().c_str()) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900236 }
237 return success;
238}
239
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900240bool ReplaceFile(const FilePath& from_path,
241 const FilePath& to_path,
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900242 File::Error* error) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900243 ThreadRestrictions::AssertIOAllowed();
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900244 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
245 return true;
246 if (error)
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900247 *error = File::OSErrorToFileError(errno);
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900248 return false;
phajdan.jr@chromium.orgd86bea02009-05-20 02:21:07 +0900249}
250
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900251bool CopyDirectory(const FilePath& from_path,
252 const FilePath& to_path,
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900253 bool recursive) {
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900254 ThreadRestrictions::AssertIOAllowed();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900255 // Some old callers of CopyDirectory want it to support wildcards.
256 // After some discussion, we decided to fix those callers.
257 // Break loudly here if anyone tries to do this.
evanm@google.com874d1672008-10-31 08:54:04 +0900258 DCHECK(to_path.value().find('*') == std::string::npos);
259 DCHECK(from_path.value().find('*') == std::string::npos);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900260
maruel@chromium.org0a177fa2014-02-06 04:55:52 +0900261 if (from_path.value().size() >= PATH_MAX) {
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900262 return false;
263 }
264
thestig@chromium.org3217c822009-08-07 06:23:07 +0900265 // This function does not properly handle destinations within the source
266 FilePath real_to_path = to_path;
brettw@chromium.org10b64122013-07-12 02:36:07 +0900267 if (PathExists(real_to_path)) {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900268 real_to_path = MakeAbsoluteFilePath(real_to_path);
269 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900270 return false;
271 } else {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900272 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
273 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900274 return false;
275 }
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900276 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
277 if (real_from_path.empty())
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900278 return false;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900279 if (real_to_path.value().size() >= real_from_path.value().size() &&
280 real_to_path.value().compare(0, real_from_path.value().size(),
maruel@chromium.org0a177fa2014-02-06 04:55:52 +0900281 real_from_path.value()) == 0) {
thestig@chromium.org3217c822009-08-07 06:23:07 +0900282 return false;
maruel@chromium.org0a177fa2014-02-06 04:55:52 +0900283 }
thestig@chromium.org3217c822009-08-07 06:23:07 +0900284
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900285 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900286 if (recursive)
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900287 traverse_type |= FileEnumerator::DIRECTORIES;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900288 FileEnumerator traversal(from_path, recursive, traverse_type);
289
vandebo@chromium.org70cf3f12009-10-14 02:57:27 +0900290 // We have to mimic windows behavior here. |to_path| may not exist yet,
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900291 // start the loop with |to_path|.
brettw@chromium.org56946722013-06-08 13:53:36 +0900292 struct stat from_stat;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900293 FilePath current = from_path;
brettw@chromium.org56946722013-06-08 13:53:36 +0900294 if (stat(from_path.value().c_str(), &from_stat) < 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900295 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
296 << from_path.value() << " errno = " << errno;
maruel@chromium.org0a177fa2014-02-06 04:55:52 +0900297 return false;
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900298 }
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900299 struct stat to_path_stat;
300 FilePath from_path_base = from_path;
301 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
302 S_ISDIR(to_path_stat.st_mode)) {
303 // If the destination already exists and is a directory, then the
304 // top level of source needs to be copied.
305 from_path_base = from_path.DirName();
306 }
307
308 // The Windows version of this function assumes that non-recursive calls
309 // will always have a directory for from_path.
maruel@chromium.org0a177fa2014-02-06 04:55:52 +0900310 // TODO(maruel): This is not necessary anymore.
brettw@chromium.org56946722013-06-08 13:53:36 +0900311 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900312
maruel@chromium.org0a177fa2014-02-06 04:55:52 +0900313 bool success = true;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900314 while (success && !current.empty()) {
aedla@chromium.orgfef1a202013-01-30 20:38:02 +0900315 // current is the source path, including from_path, so append
316 // the suffix after from_path to to_path to create the target_path.
317 FilePath target_path(to_path);
318 if (from_path_base != current) {
319 if (!from_path_base.AppendRelativePath(current, &target_path)) {
320 success = false;
321 break;
322 }
phajdan.jr@chromium.orgecf50752009-01-14 03:57:46 +0900323 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900324
brettw@chromium.org56946722013-06-08 13:53:36 +0900325 if (S_ISDIR(from_stat.st_mode)) {
326 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
thestig@chromium.org3217c822009-08-07 06:23:07 +0900327 errno != EEXIST) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900328 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
329 << target_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900330 success = false;
331 }
brettw@chromium.org56946722013-06-08 13:53:36 +0900332 } else if (S_ISREG(from_stat.st_mode)) {
thestig@chromium.org3217c822009-08-07 06:23:07 +0900333 if (!CopyFile(current, target_path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900334 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
335 << target_path.value();
thestig@chromium.org3217c822009-08-07 06:23:07 +0900336 success = false;
337 }
338 } else {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900339 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
340 << current.value();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900341 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900342
thestig@chromium.org3217c822009-08-07 06:23:07 +0900343 current = traversal.Next();
brettw@chromium.org56946722013-06-08 13:53:36 +0900344 if (!current.empty())
345 from_stat = traversal.GetInfo().stat();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900346 }
347
thestig@chromium.org3217c822009-08-07 06:23:07 +0900348 return success;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900349}
350
brettw@chromium.org10b64122013-07-12 02:36:07 +0900351bool PathExists(const FilePath& path) {
352 ThreadRestrictions::AssertIOAllowed();
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +0900353#if defined(OS_ANDROID)
354 if (path.IsContentUri()) {
355 return ContentUriExists(path);
356 }
357#endif
brettw@chromium.org10b64122013-07-12 02:36:07 +0900358 return access(path.value().c_str(), F_OK) == 0;
359}
360
brettw@chromium.org5a112e72013-07-16 05:18:09 +0900361bool PathIsWritable(const FilePath& path) {
362 ThreadRestrictions::AssertIOAllowed();
363 return access(path.value().c_str(), W_OK) == 0;
364}
365
366bool DirectoryExists(const FilePath& path) {
367 ThreadRestrictions::AssertIOAllowed();
368 stat_wrapper_t file_info;
369 if (CallStat(path.value().c_str(), &file_info) == 0)
370 return S_ISDIR(file_info.st_mode);
371 return false;
372}
373
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900374bool ReadFromFD(int fd, char* buffer, size_t bytes) {
375 size_t total_read = 0;
376 while (total_read < bytes) {
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900377 ssize_t bytes_read =
378 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
379 if (bytes_read <= 0)
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900380 break;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900381 total_read += bytes_read;
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900382 }
383 return total_read == bytes;
384}
385
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900386bool CreateSymbolicLink(const FilePath& target_path,
387 const FilePath& symlink_path) {
388 DCHECK(!symlink_path.empty());
389 DCHECK(!target_path.empty());
390 return ::symlink(target_path.value().c_str(),
391 symlink_path.value().c_str()) != -1;
392}
393
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900394bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900395 DCHECK(!symlink_path.empty());
396 DCHECK(target_path);
397 char buf[PATH_MAX];
398 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
399
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900400 if (count <= 0) {
401 target_path->clear();
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900402 return false;
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900403 }
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900404
405 *target_path = FilePath(FilePath::StringType(buf, count));
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900406 return true;
407}
408
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900409bool GetPosixFilePermissions(const FilePath& path, int* mode) {
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900410 ThreadRestrictions::AssertIOAllowed();
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900411 DCHECK(mode);
412
413 stat_wrapper_t file_info;
414 // Uses stat(), because on symbolic link, lstat() does not return valid
415 // permission bits in st_mode
416 if (CallStat(path.value().c_str(), &file_info) != 0)
417 return false;
418
419 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
420 return true;
421}
422
423bool SetPosixFilePermissions(const FilePath& path,
424 int mode) {
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900425 ThreadRestrictions::AssertIOAllowed();
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900426 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
427
428 // Calls stat() so that we can preserve the higher bits like S_ISGID.
429 stat_wrapper_t stat_buf;
430 if (CallStat(path.value().c_str(), &stat_buf) != 0)
431 return false;
432
433 // Clears the existing permission bits, and adds the new ones.
434 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
435 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
436
437 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
438 return false;
439
440 return true;
441}
442
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900443#if !defined(OS_MACOSX)
444// This is implemented in file_util_mac.mm for Mac.
445bool GetTempDir(FilePath* path) {
446 const char* tmp = getenv("TMPDIR");
447 if (tmp) {
448 *path = FilePath(tmp);
449 } else {
450#if defined(OS_ANDROID)
451 return PathService::Get(base::DIR_CACHE, path);
452#else
453 *path = FilePath("/tmp");
454#endif
455 }
456 return true;
457}
458#endif // !defined(OS_MACOSX)
459
brettw@chromium.org49de1af2014-02-20 05:34:23 +0900460#if !defined(OS_MACOSX) // Mac implementation is in file_util_mac.mm.
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900461FilePath GetHomeDir() {
462#if defined(OS_CHROMEOS)
463 if (SysInfo::IsRunningOnChromeOS())
464 return FilePath("/home/chronos/user");
465#endif
466
467 const char* home_dir = getenv("HOME");
468 if (home_dir && home_dir[0])
469 return FilePath(home_dir);
470
471#if defined(OS_ANDROID)
472 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
473#elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
brettw@chromium.org49de1af2014-02-20 05:34:23 +0900474 // g_get_home_dir calls getpwent, which can fall through to LDAP calls so
475 // this may do I/O. However, it should be rare that $HOME is not defined and
476 // this is typically called from the path service which has no threading
477 // restrictions. The path service will cache the result which limits the
478 // badness of blocking on I/O. As a result, we don't have a thread
479 // restriction here.
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900480 home_dir = g_get_home_dir();
481 if (home_dir && home_dir[0])
482 return FilePath(home_dir);
483#endif
484
485 FilePath rv;
486 if (GetTempDir(&rv))
487 return rv;
488
489 // Last resort.
490 return FilePath("/tmp");
491}
492#endif // !defined(OS_MACOSX)
493
erikkay@chromium.org18f0dde2009-08-19 01:07:55 +0900494bool CreateTemporaryFile(FilePath* path) {
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900495 ThreadRestrictions::AssertIOAllowed(); // For call to close().
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900496 FilePath directory;
497 if (!GetTempDir(&directory))
498 return false;
499 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900500 if (fd < 0)
501 return false;
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900502 close(fd);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900503 return true;
504}
505
phajdan.jr@chromium.org8139fe12009-04-28 15:50:36 +0900506FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
507 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900508 if (fd < 0)
509 return NULL;
510
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900511 FILE* file = fdopen(fd, "a+");
512 if (!file)
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900513 close(fd);
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900514 return file;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900515}
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900516
517bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900518 ThreadRestrictions::AssertIOAllowed(); // For call to close().
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900519 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900520 return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
jcampan@chromium.orgbf29e602008-10-11 03:50:32 +0900521}
522
skerner@chromium.orge4432392010-05-01 02:00:09 +0900523static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
524 const FilePath::StringType& name_tmpl,
525 FilePath* new_dir) {
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900526 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900527 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
528 << "Directory name template must contain \"XXXXXX\".";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900529
530 FilePath sub_dir = base_dir.Append(name_tmpl);
531 std::string sub_dir_string = sub_dir.value();
532
533 // this should be OK since mkdtemp just replaces characters in place
534 char* buffer = const_cast<char*>(sub_dir_string.c_str());
535 char* dtemp = mkdtemp(buffer);
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900536 if (!dtemp) {
537 DPLOG(ERROR) << "mkdtemp";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900538 return false;
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900539 }
skerner@chromium.orge4432392010-05-01 02:00:09 +0900540 *new_dir = FilePath(dtemp);
541 return true;
542}
543
544bool CreateTemporaryDirInDir(const FilePath& base_dir,
545 const FilePath::StringType& prefix,
skerner@chromium.orgbd112ab2010-06-30 16:19:11 +0900546 FilePath* new_dir) {
skerner@chromium.orge4432392010-05-01 02:00:09 +0900547 FilePath::StringType mkdtemp_template = prefix;
548 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
549 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
550}
551
erikkay@google.comcce83822008-12-24 05:20:10 +0900552bool CreateNewTempDirectory(const FilePath::StringType& prefix,
553 FilePath* new_temp_path) {
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900554 FilePath tmpdir;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900555 if (!GetTempDir(&tmpdir))
556 return false;
skerner@chromium.orge4432392010-05-01 02:00:09 +0900557
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900558 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900559}
560
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900561bool CreateDirectoryAndGetError(const FilePath& full_path,
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900562 File::Error* error) {
brettw@chromium.org738669a2013-12-04 05:08:54 +0900563 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
evanm@google.com874d1672008-10-31 08:54:04 +0900564 std::vector<FilePath> subpaths;
565
566 // Collect a list of all parent directories.
567 FilePath last_path = full_path;
568 subpaths.push_back(full_path);
569 for (FilePath path = full_path.DirName();
570 path.value() != last_path.value(); path = path.DirName()) {
571 subpaths.push_back(path);
572 last_path = path;
573 }
574
575 // Iterate through the parents and create the missing ones.
576 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
577 i != subpaths.rend(); ++i) {
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900578 if (DirectoryExists(*i))
579 continue;
580 if (mkdir(i->value().c_str(), 0700) == 0)
581 continue;
582 // Mkdir failed, but it might have failed with EEXIST, or some other error
583 // due to the the directory appearing out of thin air. This can occur if
584 // two processes are trying to create the same file system tree at the same
585 // time. Check to see if it exists and make sure it is a directory.
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900586 int saved_errno = errno;
587 if (!DirectoryExists(*i)) {
588 if (error)
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900589 *error = File::OSErrorToFileError(saved_errno);
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900590 return false;
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900591 }
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900592 }
593 return true;
594}
595
brettw@chromium.org70684242013-12-05 03:22:49 +0900596bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
597 FilePath real_path_result;
598 if (!RealPath(path, &real_path_result))
599 return false;
600
601 // To be consistant with windows, fail if |real_path_result| is a
602 // directory.
603 stat_wrapper_t file_info;
604 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
605 S_ISDIR(file_info.st_mode))
606 return false;
607
608 *normalized_path = real_path_result;
609 return true;
610}
611
brettw@chromium.orga9154032013-12-05 05:56:49 +0900612// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
613// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
614bool IsLink(const FilePath& file_path) {
615 stat_wrapper_t st;
616 // If we can't lstat the file, it's safe to assume that the file won't at
617 // least be a 'followable' link.
618 if (CallLstat(file_path.value().c_str(), &st) != 0)
619 return false;
620
621 if (S_ISLNK(st.st_mode))
622 return true;
623 else
624 return false;
625}
626
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900627bool GetFileInfo(const FilePath& file_path, File::Info* results) {
brettw@chromium.orga9154032013-12-05 05:56:49 +0900628 stat_wrapper_t file_info;
629#if defined(OS_ANDROID)
630 if (file_path.IsContentUri()) {
rvargas@chromium.org799ba6c2014-03-21 09:41:15 +0900631 File file = OpenContentUriForRead(file_path);
632 if (!file.IsValid())
brettw@chromium.orga9154032013-12-05 05:56:49 +0900633 return false;
rvargas@chromium.org799ba6c2014-03-21 09:41:15 +0900634 return file.GetInfo(results);
brettw@chromium.orga9154032013-12-05 05:56:49 +0900635 } else {
636#endif // defined(OS_ANDROID)
637 if (CallStat(file_path.value().c_str(), &file_info) != 0)
638 return false;
639#if defined(OS_ANDROID)
640 }
641#endif // defined(OS_ANDROID)
642 results->is_directory = S_ISDIR(file_info.st_mode);
643 results->size = file_info.st_size;
r.c.ladan@gmail.com733a5022014-03-11 13:11:02 +0900644#if defined(OS_MACOSX) || (defined(OS_FREEBSD) && __FreeBSD_version < 900000)
brettw@chromium.orga9154032013-12-05 05:56:49 +0900645 results->last_modified = Time::FromTimeSpec(file_info.st_mtimespec);
646 results->last_accessed = Time::FromTimeSpec(file_info.st_atimespec);
647 results->creation_time = Time::FromTimeSpec(file_info.st_ctimespec);
648#elif defined(OS_ANDROID)
649 results->last_modified = Time::FromTimeT(file_info.st_mtime);
650 results->last_accessed = Time::FromTimeT(file_info.st_atime);
651 results->creation_time = Time::FromTimeT(file_info.st_ctime);
652#else
653 results->last_modified = Time::FromTimeSpec(file_info.st_mtim);
654 results->last_accessed = Time::FromTimeSpec(file_info.st_atim);
655 results->creation_time = Time::FromTimeSpec(file_info.st_ctim);
656#endif
657 return true;
658}
659
thakis@chromium.orgf01de7e2013-12-09 06:43:30 +0900660FILE* OpenFile(const FilePath& filename, const char* mode) {
661 ThreadRestrictions::AssertIOAllowed();
662 FILE* result = NULL;
663 do {
664 result = fopen(filename.value().c_str(), mode);
665 } while (!result && errno == EINTR);
666 return result;
667}
668
669int ReadFile(const FilePath& filename, char* data, int size) {
670 ThreadRestrictions::AssertIOAllowed();
671 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
672 if (fd < 0)
673 return -1;
674
675 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
676 if (int ret = IGNORE_EINTR(close(fd)) < 0)
677 return ret;
678 return bytes_read;
679}
680
brettw@chromium.org8c7b6b82014-03-07 05:42:30 +0900681int WriteFile(const FilePath& filename, const char* data, int size) {
682 ThreadRestrictions::AssertIOAllowed();
683 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
684 if (fd < 0)
685 return -1;
686
687 int bytes_written = WriteFileDescriptor(fd, data, size);
688 if (int ret = IGNORE_EINTR(close(fd)) < 0)
689 return ret;
690 return bytes_written;
691}
692
693int WriteFileDescriptor(const int fd, const char* data, int size) {
694 // Allow for partial writes.
695 ssize_t bytes_written_total = 0;
696 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
697 bytes_written_total += bytes_written_partial) {
698 bytes_written_partial =
699 HANDLE_EINTR(write(fd, data + bytes_written_total,
700 size - bytes_written_total));
701 if (bytes_written_partial < 0)
702 return -1;
703 }
704
705 return bytes_written_total;
706}
707
brettw@chromium.org14b3aa22014-03-12 05:59:02 +0900708int AppendToFile(const FilePath& filename, const char* data, int size) {
709 ThreadRestrictions::AssertIOAllowed();
710 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
711 if (fd < 0)
712 return -1;
713
714 int bytes_written = WriteFileDescriptor(fd, data, size);
715 if (int ret = IGNORE_EINTR(close(fd)) < 0)
716 return ret;
717 return bytes_written;
718}
719
720// Gets the current working directory for the process.
721bool GetCurrentDirectory(FilePath* dir) {
722 // getcwd can return ENOENT, which implies it checks against the disk.
723 ThreadRestrictions::AssertIOAllowed();
724
725 char system_buffer[PATH_MAX] = "";
726 if (!getcwd(system_buffer, sizeof(system_buffer))) {
727 NOTREACHED();
728 return false;
729 }
730 *dir = FilePath(system_buffer);
731 return true;
732}
733
734// Sets the current working directory for the process.
735bool SetCurrentDirectory(const FilePath& path) {
736 ThreadRestrictions::AssertIOAllowed();
737 int ret = chdir(path.value().c_str());
738 return !ret;
739}
740
skerner@google.com93449ef2011-09-22 23:47:18 +0900741bool VerifyPathControlledByUser(const FilePath& base,
742 const FilePath& path,
743 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900744 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900745 if (base != path && !base.IsParent(path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900746 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
747 << base.value() << "\", path = \"" << path.value() << "\"";
skerner@google.com93449ef2011-09-22 23:47:18 +0900748 return false;
749 }
750
751 std::vector<FilePath::StringType> base_components;
752 std::vector<FilePath::StringType> path_components;
753
754 base.GetComponents(&base_components);
755 path.GetComponents(&path_components);
756
757 std::vector<FilePath::StringType>::const_iterator ib, ip;
758 for (ib = base_components.begin(), ip = path_components.begin();
759 ib != base_components.end(); ++ib, ++ip) {
760 // |base| must be a subpath of |path|, so all components should match.
761 // If these CHECKs fail, look at the test that base is a parent of
762 // path at the top of this function.
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900763 DCHECK(ip != path_components.end());
764 DCHECK(*ip == *ib);
skerner@google.com93449ef2011-09-22 23:47:18 +0900765 }
766
767 FilePath current_path = base;
skerner@chromium.org80784142011-10-18 06:30:29 +0900768 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900769 return false;
770
771 for (; ip != path_components.end(); ++ip) {
772 current_path = current_path.Append(*ip);
skerner@chromium.org80784142011-10-18 06:30:29 +0900773 if (!VerifySpecificPathControlledByUser(
774 current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900775 return false;
776 }
777 return true;
778}
779
qsr@chromium.org4ab5de92012-07-09 23:40:39 +0900780#if defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900781bool VerifyPathControlledByAdmin(const FilePath& path) {
782 const unsigned kRootUid = 0;
783 const FilePath kFileSystemRoot("/");
784
785 // The name of the administrator group on mac os.
skerner@chromium.org80784142011-10-18 06:30:29 +0900786 const char* const kAdminGroupNames[] = {
787 "admin",
788 "wheel"
789 };
skerner@google.com93449ef2011-09-22 23:47:18 +0900790
791 // Reading the groups database may touch the file system.
brettw@chromium.orgaa82a772014-03-14 02:26:21 +0900792 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +0900793
skerner@chromium.org80784142011-10-18 06:30:29 +0900794 std::set<gid_t> allowed_group_ids;
795 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
796 struct group *group_record = getgrnam(kAdminGroupNames[i]);
797 if (!group_record) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900798 DPLOG(ERROR) << "Could not get the group ID of group \""
799 << kAdminGroupNames[i] << "\".";
skerner@chromium.org80784142011-10-18 06:30:29 +0900800 continue;
801 }
802
803 allowed_group_ids.insert(group_record->gr_gid);
skerner@google.com93449ef2011-09-22 23:47:18 +0900804 }
805
806 return VerifyPathControlledByUser(
skerner@chromium.org80784142011-10-18 06:30:29 +0900807 kFileSystemRoot, path, kRootUid, allowed_group_ids);
skerner@google.com93449ef2011-09-22 23:47:18 +0900808}
stuartmorgan@chromium.org925e0b72012-07-24 20:23:32 +0900809#endif // defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900810
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900811int GetMaximumPathComponentLength(const FilePath& path) {
brettw@chromium.orgaa82a772014-03-14 02:26:21 +0900812 ThreadRestrictions::AssertIOAllowed();
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900813 return pathconf(path.value().c_str(), _PC_NAME_MAX);
814}
815
viettrungluu@chromium.org5c328d52014-03-21 06:33:39 +0900816#if !defined(OS_ANDROID)
817// This is implemented in file_util_android.cc for that platform.
viettrungluu@chromium.orgc9a4b212014-03-20 16:06:40 +0900818bool GetShmemTempDir(bool executable, FilePath* path) {
819#if defined(OS_LINUX)
820 bool use_dev_shm = true;
821 if (executable) {
822 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
823 use_dev_shm = s_dev_shm_executable;
824 }
825 if (use_dev_shm) {
826 *path = FilePath("/dev/shm");
827 return true;
828 }
829#endif
830 return GetTempDir(path);
831}
viettrungluu@chromium.org5c328d52014-03-21 06:33:39 +0900832#endif // !defined(OS_ANDROID)
viettrungluu@chromium.orgc9a4b212014-03-20 16:06:40 +0900833
brettw@chromium.orgaa82a772014-03-14 02:26:21 +0900834// -----------------------------------------------------------------------------
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900835
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900836namespace internal {
837
838bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
839 ThreadRestrictions::AssertIOAllowed();
840 // Windows compatibility: if to_path exists, from_path and to_path
841 // must be the same type, either both files, or both directories.
842 stat_wrapper_t to_file_info;
843 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
844 stat_wrapper_t from_file_info;
845 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
846 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
847 return false;
848 } else {
849 return false;
850 }
851 }
852
853 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
854 return true;
855
856 if (!CopyDirectory(from_path, to_path, true))
857 return false;
858
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900859 DeleteFile(from_path, true);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900860 return true;
861}
862
863#if !defined(OS_MACOSX)
864// Mac has its own implementation, this is for all other Posix systems.
865bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
866 ThreadRestrictions::AssertIOAllowed();
867 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
868 if (infile < 0)
869 return false;
870
871 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
872 if (outfile < 0) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900873 close(infile);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900874 return false;
875 }
876
877 const size_t kBufferSize = 32768;
878 std::vector<char> buffer(kBufferSize);
879 bool result = true;
880
881 while (result) {
882 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
883 if (bytes_read < 0) {
884 result = false;
885 break;
886 }
887 if (bytes_read == 0)
888 break;
889 // Allow for partial writes
890 ssize_t bytes_written_per_read = 0;
891 do {
892 ssize_t bytes_written_partial = HANDLE_EINTR(write(
893 outfile,
894 &buffer[bytes_written_per_read],
895 bytes_read - bytes_written_per_read));
896 if (bytes_written_partial < 0) {
897 result = false;
898 break;
899 }
900 bytes_written_per_read += bytes_written_partial;
901 } while (bytes_written_per_read < bytes_read);
902 }
903
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900904 if (IGNORE_EINTR(close(infile)) < 0)
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900905 result = false;
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900906 if (IGNORE_EINTR(close(outfile)) < 0)
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900907 result = false;
908
909 return result;
910}
911#endif // !defined(OS_MACOSX)
912
913} // namespace internal
914} // namespace base