blob: f3a7553148721a34ca190c86e5fda45646f9a5b7 [file] [log] [blame]
[email protected]011352fdf2012-03-10 00:18:311// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b2e97292008-09-02 18:20:342// 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
[email protected]4b7743de2009-04-21 01:50:397#include <dirent.h>
[email protected]21dec3872008-09-18 19:15:548#include <errno.h>
[email protected]b2e97292008-09-02 18:20:349#include <fcntl.h>
[email protected]b2e97292008-09-02 18:20:3410#include <libgen.h>
[email protected]e92dffe2010-05-12 21:36:3911#include <limits.h>
[email protected]836f1342008-10-01 17:40:1312#include <stdio.h>
[email protected]1c657852010-04-22 23:28:0513#include <stdlib.h>
[email protected]21dec3872008-09-18 19:15:5414#include <string.h>
[email protected]b2e97292008-09-02 18:20:3415#include <sys/errno.h>
[email protected]7856bb82008-12-12 23:43:0316#include <sys/mman.h>
[email protected]01e2a1f2010-05-12 15:13:5717#include <sys/param.h>
[email protected]b2e97292008-09-02 18:20:3418#include <sys/stat.h>
[email protected]ec3d1452010-02-18 10:02:2619#include <sys/time.h>
[email protected]4b7743de2009-04-21 01:50:3920#include <sys/types.h>
[email protected]b2e97292008-09-02 18:20:3421#include <time.h>
[email protected]4b7743de2009-04-21 01:50:3922#include <unistd.h>
[email protected]b2e97292008-09-02 18:20:3423
[email protected]3224dcd2009-09-16 17:31:2524#if defined(OS_MACOSX)
25#include <AvailabilityMacros.h>
[email protected]151c4a62011-04-22 04:15:1326#include "base/mac/foundation_util.h"
[email protected]6ec70cc72013-11-20 05:33:4627#elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
[email protected]4ab65012013-11-07 11:38:3228#include <glib.h> // for g_get_home_dir()
[email protected]3224dcd2009-09-16 17:31:2529#endif
30
[email protected]b2e97292008-09-02 18:20:3431#include <fstream>
32
33#include "base/basictypes.h"
[email protected]25a4c1c2013-06-08 04:53:3634#include "base/files/file_enumerator.h"
[email protected]57999812013-02-24 05:40:5235#include "base/files/file_path.h"
[email protected]b2e97292008-09-02 18:20:3436#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1537#include "base/memory/scoped_ptr.h"
38#include "base/memory/singleton.h"
[email protected]0eae7eb2012-05-17 20:09:0639#include "base/path_service.h"
[email protected]2025d002012-11-14 20:54:3540#include "base/posix/eintr_wrapper.h"
[email protected]7312f42a2011-10-17 21:30:2941#include "base/stl_util.h"
[email protected]251cd6e52013-06-11 13:36:3742#include "base/strings/string_util.h"
43#include "base/strings/stringprintf.h"
[email protected]9fe1a5b2013-02-07 19:18:0344#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:0745#include "base/strings/utf_string_conversions.h"
[email protected]49c4cf852013-09-27 19:28:2446#include "base/sys_info.h"
[email protected]34b99632011-01-01 01:01:0647#include "base/threading/thread_restrictions.h"
[email protected]99084f62013-06-28 00:49:0748#include "base/time/time.h"
[email protected]172c5502009-06-24 03:29:2649
[email protected]f7d69972011-06-21 22:34:5050#if defined(OS_ANDROID)
[email protected]f12d1e12013-11-20 07:04:5551#include "base/android/content_uri_utils.h"
[email protected]f7d69972011-06-21 22:34:5052#include "base/os_compat_android.h"
53#endif
54
[email protected]4bd46792012-07-09 14:40:3955#if !defined(OS_IOS)
56#include <grp.h>
57#endif
58
[email protected]15476932013-04-12 05:17:1559namespace base {
60
[email protected]6f5f4322010-06-09 22:56:4861namespace {
62
[email protected]07a35222012-07-19 22:24:0263#if defined(OS_BSD) || defined(OS_MACOSX)
[email protected]73e4c362011-09-22 14:47:1864typedef struct stat stat_wrapper_t;
65static int CallStat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3666 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1867 return stat(path, sb);
68}
69static int CallLstat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3670 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1871 return lstat(path, sb);
72}
73#else
74typedef struct stat64 stat_wrapper_t;
75static int CallStat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3676 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1877 return stat64(path, sb);
78}
79static int CallLstat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3680 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1881 return lstat64(path, sb);
82}
[email protected]f12d1e12013-11-20 07:04:5583#if defined(OS_ANDROID)
84static int CallFstat(int fd, stat_wrapper_t *sb) {
85 ThreadRestrictions::AssertIOAllowed();
86 return fstat64(fd, sb);
87}
88#endif
[email protected]73e4c362011-09-22 14:47:1889#endif
90
[email protected]6f5f4322010-06-09 22:56:4891// Helper for NormalizeFilePath(), defined below.
92bool RealPath(const FilePath& path, FilePath* real_path) {
[email protected]5553d5b2013-07-01 23:07:3693 ThreadRestrictions::AssertIOAllowed(); // For realpath().
[email protected]6f5f4322010-06-09 22:56:4894 FilePath::CharType buf[PATH_MAX];
95 if (!realpath(path.value().c_str(), buf))
96 return false;
97
98 *real_path = FilePath(buf);
99 return true;
100}
101
[email protected]73e4c362011-09-22 14:47:18102// Helper for VerifyPathControlledByUser.
103bool VerifySpecificPathControlledByUser(const FilePath& path,
104 uid_t owner_uid,
[email protected]7312f42a2011-10-17 21:30:29105 const std::set<gid_t>& group_gids) {
[email protected]73e4c362011-09-22 14:47:18106 stat_wrapper_t stat_info;
107 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
[email protected]a42d4632011-10-26 21:48:00108 DPLOG(ERROR) << "Failed to get information on path "
109 << path.value();
[email protected]73e4c362011-09-22 14:47:18110 return false;
111 }
[email protected]6f5f4322010-06-09 22:56:48112
[email protected]73e4c362011-09-22 14:47:18113 if (S_ISLNK(stat_info.st_mode)) {
[email protected]a42d4632011-10-26 21:48:00114 DLOG(ERROR) << "Path " << path.value()
[email protected]73e4c362011-09-22 14:47:18115 << " is a symbolic link.";
116 return false;
117 }
118
119 if (stat_info.st_uid != owner_uid) {
[email protected]a42d4632011-10-26 21:48:00120 DLOG(ERROR) << "Path " << path.value()
121 << " is owned by the wrong user.";
[email protected]73e4c362011-09-22 14:47:18122 return false;
123 }
124
[email protected]7312f42a2011-10-17 21:30:29125 if ((stat_info.st_mode & S_IWGRP) &&
126 !ContainsKey(group_gids, stat_info.st_gid)) {
[email protected]a42d4632011-10-26 21:48:00127 DLOG(ERROR) << "Path " << path.value()
128 << " is writable by an unprivileged group.";
[email protected]73e4c362011-09-22 14:47:18129 return false;
130 }
131
132 if (stat_info.st_mode & S_IWOTH) {
[email protected]a42d4632011-10-26 21:48:00133 DLOG(ERROR) << "Path " << path.value()
134 << " is writable by any user.";
[email protected]73e4c362011-09-22 14:47:18135 return false;
136 }
137
138 return true;
[email protected]fb66f9d2009-09-07 16:39:46139}
[email protected]73e4c362011-09-22 14:47:18140
[email protected]5553d5b2013-07-01 23:07:36141std::string TempFileName() {
142#if defined(OS_MACOSX)
143 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
144#endif
145
146#if defined(GOOGLE_CHROME_BUILD)
147 return std::string(".com.google.Chrome.XXXXXX");
148#else
149 return std::string(".org.chromium.Chromium.XXXXXX");
150#endif
151}
152
[email protected]fb4bcfa32013-12-02 18:55:49153// Creates and opens a temporary file in |directory|, returning the
154// file descriptor. |path| is set to the temporary file path.
155// This function does NOT unlink() the file.
156int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
157 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
158 *path = directory.Append(base::TempFileName());
159 const std::string& tmpdir_string = path->value();
160 // this should be OK since mkstemp just replaces characters in place
161 char* buffer = const_cast<char*>(tmpdir_string.c_str());
162
163 return HANDLE_EINTR(mkstemp(buffer));
164}
165
166#if defined(OS_LINUX)
167// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
168// This depends on the mount options used for /dev/shm, which vary among
169// different Linux distributions and possibly local configuration. It also
170// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
171// but its kernel allows mprotect with PROT_EXEC anyway.
172bool DetermineDevShmExecutable() {
173 bool result = false;
174 FilePath path;
175 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
176 if (fd >= 0) {
177 file_util::ScopedFD shm_fd_closer(&fd);
178 DeleteFile(path, false);
179 long sysconf_result = sysconf(_SC_PAGESIZE);
180 CHECK_GE(sysconf_result, 0);
181 size_t pagesize = static_cast<size_t>(sysconf_result);
182 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
183 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
184 if (mapping != MAP_FAILED) {
185 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
186 result = true;
187 munmap(mapping, pagesize);
188 }
189 }
190 return result;
191}
192#endif // defined(OS_LINUX)
193
[email protected]73e4c362011-09-22 14:47:18194} // namespace
[email protected]fb66f9d2009-09-07 16:39:46195
[email protected]918efbf2013-07-01 19:41:02196FilePath MakeAbsoluteFilePath(const FilePath& input) {
197 ThreadRestrictions::AssertIOAllowed();
198 char full_path[PATH_MAX];
199 if (realpath(input.value().c_str(), full_path) == NULL)
200 return FilePath();
201 return FilePath(full_path);
[email protected]151c4a62011-04-22 04:15:13202}
[email protected]778e8c52008-09-11 17:36:23203
[email protected]b2e97292008-09-02 18:20:34204// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
205// which works both with and without the recursive flag. I'm not sure we need
206// that functionality. If not, remove from file_util_win.cc, otherwise add it
207// here.
[email protected]dd3aa792013-07-16 19:10:23208bool DeleteFile(const FilePath& path, bool recursive) {
[email protected]918efbf2013-07-01 19:41:02209 ThreadRestrictions::AssertIOAllowed();
[email protected]640517f2008-10-30 23:54:04210 const char* path_str = path.value().c_str();
[email protected]fb66f9d2009-09-07 16:39:46211 stat_wrapper_t file_info;
[email protected]7122db22012-06-30 05:26:59212 int test = CallLstat(path_str, &file_info);
[email protected]b2e97292008-09-02 18:20:34213 if (test != 0) {
214 // The Windows version defines this condition as success.
[email protected]9e51af92009-02-04 00:58:39215 bool ret = (errno == ENOENT || errno == ENOTDIR);
[email protected]b2e97292008-09-02 18:20:34216 return ret;
217 }
218 if (!S_ISDIR(file_info.st_mode))
[email protected]640517f2008-10-30 23:54:04219 return (unlink(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34220 if (!recursive)
[email protected]640517f2008-10-30 23:54:04221 return (rmdir(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34222
223 bool success = true;
[email protected]49930c3a2009-08-06 21:23:07224 std::stack<std::string> directories;
225 directories.push(path.value());
[email protected]84c3f162012-08-12 01:57:23226 FileEnumerator traversal(path, true,
227 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
228 FileEnumerator::SHOW_SYM_LINKS);
[email protected]49930c3a2009-08-06 21:23:07229 for (FilePath current = traversal.Next(); success && !current.empty();
230 current = traversal.Next()) {
[email protected]25a4c1c2013-06-08 04:53:36231 if (traversal.GetInfo().IsDirectory())
[email protected]49930c3a2009-08-06 21:23:07232 directories.push(current.value());
233 else
234 success = (unlink(current.value().c_str()) == 0);
[email protected]21dec3872008-09-18 19:15:54235 }
[email protected]49930c3a2009-08-06 21:23:07236
237 while (success && !directories.empty()) {
238 FilePath dir = FilePath(directories.top());
239 directories.pop();
240 success = (rmdir(dir.value().c_str()) == 0);
[email protected]b2e97292008-09-02 18:20:34241 }
242 return success;
243}
244
[email protected]5553d5b2013-07-01 23:07:36245bool ReplaceFile(const FilePath& from_path,
246 const FilePath& to_path,
247 PlatformFileError* error) {
248 ThreadRestrictions::AssertIOAllowed();
[email protected]6f5399412013-05-08 22:02:36249 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
250 return true;
251 if (error)
[email protected]5553d5b2013-07-01 23:07:36252 *error = ErrnoToPlatformFileError(errno);
[email protected]6f5399412013-05-08 22:02:36253 return false;
[email protected]c5866dca2009-05-19 17:21:07254}
255
[email protected]9e66a9b2013-05-08 05:46:20256bool CopyDirectory(const FilePath& from_path,
257 const FilePath& to_path,
[email protected]21dec3872008-09-18 19:15:54258 bool recursive) {
[email protected]f0ff2ad2013-07-09 17:42:26259 ThreadRestrictions::AssertIOAllowed();
[email protected]21dec3872008-09-18 19:15:54260 // Some old callers of CopyDirectory want it to support wildcards.
261 // After some discussion, we decided to fix those callers.
262 // Break loudly here if anyone tries to do this.
[email protected]9e66a9b2013-05-08 05:46:20263 // TODO(evanm): remove this once we're sure it's ok.
[email protected]640517f2008-10-30 23:54:04264 DCHECK(to_path.value().find('*') == std::string::npos);
265 DCHECK(from_path.value().find('*') == std::string::npos);
[email protected]21dec3872008-09-18 19:15:54266
267 char top_dir[PATH_MAX];
[email protected]f0ff2ad2013-07-09 17:42:26268 if (strlcpy(top_dir, from_path.value().c_str(),
269 arraysize(top_dir)) >= arraysize(top_dir)) {
[email protected]21dec3872008-09-18 19:15:54270 return false;
271 }
272
[email protected]49930c3a2009-08-06 21:23:07273 // This function does not properly handle destinations within the source
274 FilePath real_to_path = to_path;
[email protected]7567484142013-07-11 17:36:07275 if (PathExists(real_to_path)) {
[email protected]15476932013-04-12 05:17:15276 real_to_path = MakeAbsoluteFilePath(real_to_path);
277 if (real_to_path.empty())
[email protected]49930c3a2009-08-06 21:23:07278 return false;
279 } else {
[email protected]15476932013-04-12 05:17:15280 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
281 if (real_to_path.empty())
[email protected]49930c3a2009-08-06 21:23:07282 return false;
283 }
[email protected]15476932013-04-12 05:17:15284 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
285 if (real_from_path.empty())
[email protected]21dec3872008-09-18 19:15:54286 return false;
[email protected]49930c3a2009-08-06 21:23:07287 if (real_to_path.value().size() >= real_from_path.value().size() &&
288 real_to_path.value().compare(0, real_from_path.value().size(),
289 real_from_path.value()) == 0)
290 return false;
291
292 bool success = true;
[email protected]84c3f162012-08-12 01:57:23293 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
[email protected]49930c3a2009-08-06 21:23:07294 if (recursive)
[email protected]84c3f162012-08-12 01:57:23295 traverse_type |= FileEnumerator::DIRECTORIES;
[email protected]49930c3a2009-08-06 21:23:07296 FileEnumerator traversal(from_path, recursive, traverse_type);
297
[email protected]abbc5732009-10-13 17:57:27298 // We have to mimic windows behavior here. |to_path| may not exist yet,
[email protected]bc6a9012009-10-15 01:11:44299 // start the loop with |to_path|.
[email protected]25a4c1c2013-06-08 04:53:36300 struct stat from_stat;
[email protected]49930c3a2009-08-06 21:23:07301 FilePath current = from_path;
[email protected]25a4c1c2013-06-08 04:53:36302 if (stat(from_path.value().c_str(), &from_stat) < 0) {
[email protected]a42d4632011-10-26 21:48:00303 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
304 << from_path.value() << " errno = " << errno;
[email protected]49930c3a2009-08-06 21:23:07305 success = false;
[email protected]21dec3872008-09-18 19:15:54306 }
[email protected]bc6a9012009-10-15 01:11:44307 struct stat to_path_stat;
308 FilePath from_path_base = from_path;
309 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
310 S_ISDIR(to_path_stat.st_mode)) {
311 // If the destination already exists and is a directory, then the
312 // top level of source needs to be copied.
313 from_path_base = from_path.DirName();
314 }
315
316 // The Windows version of this function assumes that non-recursive calls
317 // will always have a directory for from_path.
[email protected]25a4c1c2013-06-08 04:53:36318 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
[email protected]21dec3872008-09-18 19:15:54319
[email protected]49930c3a2009-08-06 21:23:07320 while (success && !current.empty()) {
[email protected]92e06492013-01-30 11:38:02321 // current is the source path, including from_path, so append
322 // the suffix after from_path to to_path to create the target_path.
323 FilePath target_path(to_path);
324 if (from_path_base != current) {
325 if (!from_path_base.AppendRelativePath(current, &target_path)) {
326 success = false;
327 break;
328 }
[email protected]ca0209612009-01-13 18:57:46329 }
[email protected]21dec3872008-09-18 19:15:54330
[email protected]25a4c1c2013-06-08 04:53:36331 if (S_ISDIR(from_stat.st_mode)) {
332 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
[email protected]49930c3a2009-08-06 21:23:07333 errno != EEXIST) {
[email protected]a42d4632011-10-26 21:48:00334 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
335 << target_path.value() << " errno = " << errno;
[email protected]49930c3a2009-08-06 21:23:07336 success = false;
337 }
[email protected]25a4c1c2013-06-08 04:53:36338 } else if (S_ISREG(from_stat.st_mode)) {
[email protected]49930c3a2009-08-06 21:23:07339 if (!CopyFile(current, target_path)) {
[email protected]a42d4632011-10-26 21:48:00340 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
341 << target_path.value();
[email protected]49930c3a2009-08-06 21:23:07342 success = false;
343 }
344 } else {
[email protected]a42d4632011-10-26 21:48:00345 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
346 << current.value();
[email protected]21dec3872008-09-18 19:15:54347 }
[email protected]21dec3872008-09-18 19:15:54348
[email protected]49930c3a2009-08-06 21:23:07349 current = traversal.Next();
[email protected]25a4c1c2013-06-08 04:53:36350 if (!current.empty())
351 from_stat = traversal.GetInfo().stat();
[email protected]21dec3872008-09-18 19:15:54352 }
353
[email protected]49930c3a2009-08-06 21:23:07354 return success;
[email protected]b2e97292008-09-02 18:20:34355}
356
[email protected]7567484142013-07-11 17:36:07357bool PathExists(const FilePath& path) {
358 ThreadRestrictions::AssertIOAllowed();
[email protected]f12d1e12013-11-20 07:04:55359#if defined(OS_ANDROID)
360 if (path.IsContentUri()) {
361 return ContentUriExists(path);
362 }
363#endif
[email protected]7567484142013-07-11 17:36:07364 return access(path.value().c_str(), F_OK) == 0;
365}
366
[email protected]dcd16612013-07-15 20:18:09367bool PathIsWritable(const FilePath& path) {
368 ThreadRestrictions::AssertIOAllowed();
369 return access(path.value().c_str(), W_OK) == 0;
370}
371
372bool DirectoryExists(const FilePath& path) {
373 ThreadRestrictions::AssertIOAllowed();
374 stat_wrapper_t file_info;
375 if (CallStat(path.value().c_str(), &file_info) == 0)
376 return S_ISDIR(file_info.st_mode);
377 return false;
378}
379
[email protected]45301492009-04-23 12:38:08380bool ReadFromFD(int fd, char* buffer, size_t bytes) {
381 size_t total_read = 0;
382 while (total_read < bytes) {
[email protected]157c61b2009-05-01 21:37:31383 ssize_t bytes_read =
384 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
385 if (bytes_read <= 0)
[email protected]45301492009-04-23 12:38:08386 break;
[email protected]157c61b2009-05-01 21:37:31387 total_read += bytes_read;
[email protected]45301492009-04-23 12:38:08388 }
389 return total_read == bytes;
390}
391
[email protected]2e733d102010-11-30 00:43:37392bool CreateSymbolicLink(const FilePath& target_path,
393 const FilePath& symlink_path) {
394 DCHECK(!symlink_path.empty());
395 DCHECK(!target_path.empty());
396 return ::symlink(target_path.value().c_str(),
397 symlink_path.value().c_str()) != -1;
398}
399
[email protected]b264eab2013-11-27 23:22:08400bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
[email protected]2e733d102010-11-30 00:43:37401 DCHECK(!symlink_path.empty());
402 DCHECK(target_path);
403 char buf[PATH_MAX];
404 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
405
[email protected]723571a2010-12-03 17:37:54406 if (count <= 0) {
407 target_path->clear();
[email protected]2e733d102010-11-30 00:43:37408 return false;
[email protected]723571a2010-12-03 17:37:54409 }
[email protected]2e733d102010-11-30 00:43:37410
411 *target_path = FilePath(FilePath::StringType(buf, count));
[email protected]2e733d102010-11-30 00:43:37412 return true;
413}
414
[email protected]5085e442012-07-11 01:24:02415bool GetPosixFilePermissions(const FilePath& path, int* mode) {
[email protected]b264eab2013-11-27 23:22:08416 ThreadRestrictions::AssertIOAllowed();
[email protected]5085e442012-07-11 01:24:02417 DCHECK(mode);
418
419 stat_wrapper_t file_info;
420 // Uses stat(), because on symbolic link, lstat() does not return valid
421 // permission bits in st_mode
422 if (CallStat(path.value().c_str(), &file_info) != 0)
423 return false;
424
425 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
426 return true;
427}
428
429bool SetPosixFilePermissions(const FilePath& path,
430 int mode) {
[email protected]b264eab2013-11-27 23:22:08431 ThreadRestrictions::AssertIOAllowed();
[email protected]5085e442012-07-11 01:24:02432 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
433
434 // Calls stat() so that we can preserve the higher bits like S_ISGID.
435 stat_wrapper_t stat_buf;
436 if (CallStat(path.value().c_str(), &stat_buf) != 0)
437 return false;
438
439 // Clears the existing permission bits, and adds the new ones.
440 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
441 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
442
443 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
444 return false;
445
446 return true;
447}
448
[email protected]fb4bcfa32013-12-02 18:55:49449#if !defined(OS_MACOSX)
450// This is implemented in file_util_mac.mm for Mac.
451bool GetTempDir(FilePath* path) {
452 const char* tmp = getenv("TMPDIR");
453 if (tmp) {
454 *path = FilePath(tmp);
455 } else {
456#if defined(OS_ANDROID)
457 return PathService::Get(base::DIR_CACHE, path);
458#else
459 *path = FilePath("/tmp");
460#endif
461 }
462 return true;
463}
464#endif // !defined(OS_MACOSX)
465
466#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
467// This is implemented in file_util_mac.mm and file_util_android.cc for those
468// platforms.
469bool GetShmemTempDir(bool executable, FilePath* path) {
470#if defined(OS_LINUX)
471 bool use_dev_shm = true;
472 if (executable) {
473 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
474 use_dev_shm = s_dev_shm_executable;
475 }
476 if (use_dev_shm) {
477 *path = FilePath("/dev/shm");
478 return true;
479 }
480#endif
481 return GetTempDir(path);
482}
483#endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
484
485#if !defined(OS_MACOSX)
486FilePath GetHomeDir() {
487#if defined(OS_CHROMEOS)
488 if (SysInfo::IsRunningOnChromeOS())
489 return FilePath("/home/chronos/user");
490#endif
491
492 const char* home_dir = getenv("HOME");
493 if (home_dir && home_dir[0])
494 return FilePath(home_dir);
495
496#if defined(OS_ANDROID)
497 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
498#elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
499 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
500 ThreadRestrictions::AssertIOAllowed();
501
502 home_dir = g_get_home_dir();
503 if (home_dir && home_dir[0])
504 return FilePath(home_dir);
505#endif
506
507 FilePath rv;
508 if (GetTempDir(&rv))
509 return rv;
510
511 // Last resort.
512 return FilePath("/tmp");
513}
514#endif // !defined(OS_MACOSX)
515
[email protected]33edeab2009-08-18 16:07:55516bool CreateTemporaryFile(FilePath* path) {
[email protected]03d9afc02013-12-03 17:55:52517 ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]9e51af92009-02-04 00:58:39518 FilePath directory;
519 if (!GetTempDir(&directory))
520 return false;
521 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
[email protected]b2e97292008-09-02 18:20:34522 if (fd < 0)
523 return false;
[email protected]d89eec82013-12-03 14:10:59524 close(fd);
[email protected]b2e97292008-09-02 18:20:34525 return true;
526}
527
[email protected]103dccfa2011-12-06 18:07:05528FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
[email protected]9e51af92009-02-04 00:58:39529 FilePath directory;
[email protected]fb4bcfa32013-12-02 18:55:49530 if (!GetShmemTempDir(executable, &directory))
[email protected]628476aa2010-06-10 22:56:23531 return NULL;
[email protected]9e51af92009-02-04 00:58:39532
[email protected]6faa0e0d2009-04-28 06:50:36533 return CreateAndOpenTemporaryFileInDir(directory, path);
534}
535
536FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
537 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
[email protected]9e51af92009-02-04 00:58:39538 if (fd < 0)
539 return NULL;
540
[email protected]139063bd2011-04-18 19:05:53541 FILE* file = fdopen(fd, "a+");
542 if (!file)
[email protected]d89eec82013-12-03 14:10:59543 close(fd);
[email protected]139063bd2011-04-18 19:05:53544 return file;
[email protected]9e51af92009-02-04 00:58:39545}
[email protected]6445c402009-09-11 20:06:27546
547bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
[email protected]03d9afc02013-12-03 17:55:52548 ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]6445c402009-09-11 20:06:27549 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
[email protected]d89eec82013-12-03 14:10:59550 return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
[email protected]9ccbb372008-10-10 18:50:32551}
552
[email protected]b0b3abd92010-04-30 17:00:09553static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
554 const FilePath::StringType& name_tmpl,
555 FilePath* new_dir) {
[email protected]03d9afc02013-12-03 17:55:52556 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
[email protected]a42d4632011-10-26 21:48:00557 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
558 << "Directory name template must contain \"XXXXXX\".";
[email protected]b0b3abd92010-04-30 17:00:09559
560 FilePath sub_dir = base_dir.Append(name_tmpl);
561 std::string sub_dir_string = sub_dir.value();
562
563 // this should be OK since mkdtemp just replaces characters in place
564 char* buffer = const_cast<char*>(sub_dir_string.c_str());
565 char* dtemp = mkdtemp(buffer);
[email protected]3ad035d22010-07-28 21:00:51566 if (!dtemp) {
567 DPLOG(ERROR) << "mkdtemp";
[email protected]b0b3abd92010-04-30 17:00:09568 return false;
[email protected]3ad035d22010-07-28 21:00:51569 }
[email protected]b0b3abd92010-04-30 17:00:09570 *new_dir = FilePath(dtemp);
571 return true;
572}
573
574bool CreateTemporaryDirInDir(const FilePath& base_dir,
575 const FilePath::StringType& prefix,
[email protected]046062e82010-06-30 07:19:11576 FilePath* new_dir) {
[email protected]b0b3abd92010-04-30 17:00:09577 FilePath::StringType mkdtemp_template = prefix;
578 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
579 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
580}
581
[email protected]7e1fde6a2008-12-23 20:20:10582bool CreateNewTempDirectory(const FilePath::StringType& prefix,
583 FilePath* new_temp_path) {
[email protected]392264c2008-11-11 00:01:38584 FilePath tmpdir;
[email protected]b2e97292008-09-02 18:20:34585 if (!GetTempDir(&tmpdir))
586 return false;
[email protected]b0b3abd92010-04-30 17:00:09587
[email protected]03d9afc02013-12-03 17:55:52588 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
[email protected]b2e97292008-09-02 18:20:34589}
590
[email protected]cfd23d22013-06-11 03:50:25591bool CreateDirectoryAndGetError(const FilePath& full_path,
[email protected]426d1c92013-12-03 20:08:54592 PlatformFileError* error) {
593 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
[email protected]640517f2008-10-30 23:54:04594 std::vector<FilePath> subpaths;
595
596 // Collect a list of all parent directories.
597 FilePath last_path = full_path;
598 subpaths.push_back(full_path);
599 for (FilePath path = full_path.DirName();
600 path.value() != last_path.value(); path = path.DirName()) {
601 subpaths.push_back(path);
602 last_path = path;
603 }
604
605 // Iterate through the parents and create the missing ones.
606 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
607 i != subpaths.rend(); ++i) {
[email protected]0ba86e42010-03-17 21:39:42608 if (DirectoryExists(*i))
609 continue;
610 if (mkdir(i->value().c_str(), 0700) == 0)
611 continue;
612 // Mkdir failed, but it might have failed with EEXIST, or some other error
613 // due to the the directory appearing out of thin air. This can occur if
614 // two processes are trying to create the same file system tree at the same
615 // time. Check to see if it exists and make sure it is a directory.
[email protected]cfd23d22013-06-11 03:50:25616 int saved_errno = errno;
617 if (!DirectoryExists(*i)) {
618 if (error)
[email protected]426d1c92013-12-03 20:08:54619 *error = ErrnoToPlatformFileError(saved_errno);
[email protected]0ba86e42010-03-17 21:39:42620 return false;
[email protected]cfd23d22013-06-11 03:50:25621 }
[email protected]b2e97292008-09-02 18:20:34622 }
623 return true;
624}
625
[email protected]56285702013-12-04 18:22:49626bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
627 FilePath real_path_result;
628 if (!RealPath(path, &real_path_result))
629 return false;
630
631 // To be consistant with windows, fail if |real_path_result| is a
632 // directory.
633 stat_wrapper_t file_info;
634 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
635 S_ISDIR(file_info.st_mode))
636 return false;
637
638 *normalized_path = real_path_result;
639 return true;
640}
641
[email protected]426d1c92013-12-03 20:08:54642} // namespace base
643
644// -----------------------------------------------------------------------------
645
646namespace file_util {
647
648using base::stat_wrapper_t;
649using base::CallStat;
650using base::CallLstat;
651using base::CreateAndOpenFdForTemporaryFile;
652using base::DirectoryExists;
653using base::FileEnumerator;
654using base::FilePath;
655using base::MakeAbsoluteFilePath;
[email protected]426d1c92013-12-03 20:08:54656using base::VerifySpecificPathControlledByUser;
657
[email protected]992c73e2013-04-04 09:05:21658base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
659 const int kMaxAttempts = 20;
660 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
[email protected]007b3f82013-04-09 08:46:45661 int uniquifier =
662 GetUniquePathNumber(path, base::FilePath::StringType());
[email protected]992c73e2013-04-04 09:05:21663 if (uniquifier < 0)
664 break;
665 base::FilePath test_path = (uniquifier == 0) ? path :
666 path.InsertBeforeExtensionASCII(
667 base::StringPrintf(" (%d)", uniquifier));
668 if (mkdir(test_path.value().c_str(), 0777) == 0)
669 return test_path;
670 else if (errno != EEXIST)
671 break;
672 }
673 return base::FilePath();
674}
675
[email protected]cd78ad52011-05-31 23:10:06676// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
677// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
678bool IsLink(const FilePath& file_path) {
[email protected]7122db22012-06-30 05:26:59679 stat_wrapper_t st;
[email protected]cd78ad52011-05-31 23:10:06680 // If we can't lstat the file, it's safe to assume that the file won't at
681 // least be a 'followable' link.
[email protected]7122db22012-06-30 05:26:59682 if (CallLstat(file_path.value().c_str(), &st) != 0)
[email protected]cd78ad52011-05-31 23:10:06683 return false;
684
685 if (S_ISLNK(st.st_mode))
686 return true;
687 else
688 return false;
689}
690
[email protected]2f0193c22010-09-03 02:28:37691bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
[email protected]fb66f9d2009-09-07 16:39:46692 stat_wrapper_t file_info;
[email protected]f12d1e12013-11-20 07:04:55693#if defined(OS_ANDROID)
694 if (file_path.IsContentUri()) {
695 int fd = OpenContentUriForRead(file_path);
696 if (fd < 0)
697 return false;
698 ScopedFD scoped_fd(&fd);
699 if (base::CallFstat(fd, &file_info) != 0)
700 return false;
701 } else {
702#endif // defined(OS_ANDROID)
703 if (CallStat(file_path.value().c_str(), &file_info) != 0)
704 return false;
705#if defined(OS_ANDROID)
706 }
707#endif // defined(OS_ANDROID)
[email protected]f5e3da4d2008-09-26 01:04:08708 results->is_directory = S_ISDIR(file_info.st_mode);
709 results->size = file_info.st_size;
[email protected]92bb9cb2013-06-10 09:41:35710#if defined(OS_MACOSX)
711 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
712 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
713 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
714#elif defined(OS_ANDROID)
[email protected]5ef323892009-07-24 16:13:53715 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
[email protected]2f0193c22010-09-03 02:28:37716 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
717 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
[email protected]92bb9cb2013-06-10 09:41:35718#else
719 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
720 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
721 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
722#endif
[email protected]b2e97292008-09-02 18:20:34723 return true;
724}
725
[email protected]825003f2009-05-14 17:49:23726bool GetInode(const FilePath& path, ino_t* inode) {
[email protected]ba74b0d22010-10-23 05:19:20727 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
[email protected]825003f2009-05-14 17:49:23728 struct stat buffer;
729 int result = stat(path.value().c_str(), &buffer);
730 if (result < 0)
731 return false;
732
733 *inode = buffer.st_ino;
734 return true;
735}
736
[email protected]836f1342008-10-01 17:40:13737FILE* OpenFile(const std::string& filename, const char* mode) {
[email protected]a9cd2a652008-11-17 21:01:19738 return OpenFile(FilePath(filename), mode);
[email protected]836f1342008-10-01 17:40:13739}
740
[email protected]a9cd2a652008-11-17 21:01:19741FILE* OpenFile(const FilePath& filename, const char* mode) {
[email protected]ba74b0d22010-10-23 05:19:20742 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25743 FILE* result = NULL;
744 do {
745 result = fopen(filename.value().c_str(), mode);
746 } while (!result && errno == EINTR);
747 return result;
[email protected]836f1342008-10-01 17:40:13748}
749
[email protected]c870c762009-01-28 05:47:15750int ReadFile(const FilePath& filename, char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20751 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25752 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
[email protected]b2e97292008-09-02 18:20:34753 if (fd < 0)
754 return -1;
[email protected]a9cd2a652008-11-17 21:01:19755
[email protected]cabe39c2010-02-02 02:28:16756 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
[email protected]d89eec82013-12-03 14:10:59757 if (int ret = IGNORE_EINTR(close(fd)) < 0)
[email protected]cabe39c2010-02-02 02:28:16758 return ret;
759 return bytes_read;
[email protected]b2e97292008-09-02 18:20:34760}
761
[email protected]c870c762009-01-28 05:47:15762int WriteFile(const FilePath& filename, const char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20763 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25764 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
[email protected]b2e97292008-09-02 18:20:34765 if (fd < 0)
766 return -1;
[email protected]778e8c52008-09-11 17:36:23767
[email protected]cabe39c2010-02-02 02:28:16768 int bytes_written = WriteFileDescriptor(fd, data, size);
[email protected]d89eec82013-12-03 14:10:59769 if (int ret = IGNORE_EINTR(close(fd)) < 0)
[email protected]cabe39c2010-02-02 02:28:16770 return ret;
771 return bytes_written;
[email protected]fbea0232009-09-16 00:29:22772}
773
774int WriteFileDescriptor(const int fd, const char* data, int size) {
775 // Allow for partial writes.
776 ssize_t bytes_written_total = 0;
777 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
778 bytes_written_total += bytes_written_partial) {
779 bytes_written_partial =
780 HANDLE_EINTR(write(fd, data + bytes_written_total,
781 size - bytes_written_total));
782 if (bytes_written_partial < 0)
783 return -1;
784 }
785
[email protected]778e8c52008-09-11 17:36:23786 return bytes_written_total;
[email protected]b2e97292008-09-02 18:20:34787}
788
[email protected]891128f2012-04-29 12:57:10789int AppendToFile(const FilePath& filename, const char* data, int size) {
790 base::ThreadRestrictions::AssertIOAllowed();
791 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
792 if (fd < 0)
793 return -1;
794
795 int bytes_written = WriteFileDescriptor(fd, data, size);
[email protected]d89eec82013-12-03 14:10:59796 if (int ret = IGNORE_EINTR(close(fd)) < 0)
[email protected]891128f2012-04-29 12:57:10797 return ret;
798 return bytes_written;
799}
800
[email protected]b2e97292008-09-02 18:20:34801// Gets the current working directory for the process.
[email protected]640517f2008-10-30 23:54:04802bool GetCurrentDirectory(FilePath* dir) {
[email protected]ba74b0d22010-10-23 05:19:20803 // getcwd can return ENOENT, which implies it checks against the disk.
804 base::ThreadRestrictions::AssertIOAllowed();
805
[email protected]b2e97292008-09-02 18:20:34806 char system_buffer[PATH_MAX] = "";
[email protected]640517f2008-10-30 23:54:04807 if (!getcwd(system_buffer, sizeof(system_buffer))) {
808 NOTREACHED();
809 return false;
810 }
811 *dir = FilePath(system_buffer);
[email protected]b2e97292008-09-02 18:20:34812 return true;
813}
814
815// Sets the current working directory for the process.
[email protected]a9cd2a652008-11-17 21:01:19816bool SetCurrentDirectory(const FilePath& path) {
[email protected]ba74b0d22010-10-23 05:19:20817 base::ThreadRestrictions::AssertIOAllowed();
[email protected]a9cd2a652008-11-17 21:01:19818 int ret = chdir(path.value().c_str());
819 return !ret;
[email protected]b2e97292008-09-02 18:20:34820}
[email protected]a9cd2a652008-11-17 21:01:19821
[email protected]73e4c362011-09-22 14:47:18822bool VerifyPathControlledByUser(const FilePath& base,
823 const FilePath& path,
824 uid_t owner_uid,
[email protected]7312f42a2011-10-17 21:30:29825 const std::set<gid_t>& group_gids) {
[email protected]73e4c362011-09-22 14:47:18826 if (base != path && !base.IsParent(path)) {
[email protected]a42d4632011-10-26 21:48:00827 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
828 << base.value() << "\", path = \"" << path.value() << "\"";
[email protected]73e4c362011-09-22 14:47:18829 return false;
830 }
831
832 std::vector<FilePath::StringType> base_components;
833 std::vector<FilePath::StringType> path_components;
834
835 base.GetComponents(&base_components);
836 path.GetComponents(&path_components);
837
838 std::vector<FilePath::StringType>::const_iterator ib, ip;
839 for (ib = base_components.begin(), ip = path_components.begin();
840 ib != base_components.end(); ++ib, ++ip) {
841 // |base| must be a subpath of |path|, so all components should match.
842 // If these CHECKs fail, look at the test that base is a parent of
843 // path at the top of this function.
[email protected]a42d4632011-10-26 21:48:00844 DCHECK(ip != path_components.end());
845 DCHECK(*ip == *ib);
[email protected]73e4c362011-09-22 14:47:18846 }
847
848 FilePath current_path = base;
[email protected]7312f42a2011-10-17 21:30:29849 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
[email protected]73e4c362011-09-22 14:47:18850 return false;
851
852 for (; ip != path_components.end(); ++ip) {
853 current_path = current_path.Append(*ip);
[email protected]7312f42a2011-10-17 21:30:29854 if (!VerifySpecificPathControlledByUser(
855 current_path, owner_uid, group_gids))
[email protected]73e4c362011-09-22 14:47:18856 return false;
857 }
858 return true;
859}
860
[email protected]4bd46792012-07-09 14:40:39861#if defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]73e4c362011-09-22 14:47:18862bool VerifyPathControlledByAdmin(const FilePath& path) {
863 const unsigned kRootUid = 0;
864 const FilePath kFileSystemRoot("/");
865
866 // The name of the administrator group on mac os.
[email protected]7312f42a2011-10-17 21:30:29867 const char* const kAdminGroupNames[] = {
868 "admin",
869 "wheel"
870 };
[email protected]73e4c362011-09-22 14:47:18871
872 // Reading the groups database may touch the file system.
873 base::ThreadRestrictions::AssertIOAllowed();
874
[email protected]7312f42a2011-10-17 21:30:29875 std::set<gid_t> allowed_group_ids;
876 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
877 struct group *group_record = getgrnam(kAdminGroupNames[i]);
878 if (!group_record) {
[email protected]a42d4632011-10-26 21:48:00879 DPLOG(ERROR) << "Could not get the group ID of group \""
880 << kAdminGroupNames[i] << "\".";
[email protected]7312f42a2011-10-17 21:30:29881 continue;
882 }
883
884 allowed_group_ids.insert(group_record->gr_gid);
[email protected]73e4c362011-09-22 14:47:18885 }
886
887 return VerifyPathControlledByUser(
[email protected]7312f42a2011-10-17 21:30:29888 kFileSystemRoot, path, kRootUid, allowed_group_ids);
[email protected]73e4c362011-09-22 14:47:18889}
[email protected]eba29932012-07-24 11:23:32890#endif // defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]73e4c362011-09-22 14:47:18891
[email protected]59480302013-02-21 03:24:08892int GetMaximumPathComponentLength(const FilePath& path) {
893 base::ThreadRestrictions::AssertIOAllowed();
894 return pathconf(path.value().c_str(), _PC_NAME_MAX);
895}
896
[email protected]33e585a2010-11-20 03:38:15897} // namespace file_util
[email protected]f0ff2ad2013-07-09 17:42:26898
899namespace base {
900namespace internal {
901
902bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
903 ThreadRestrictions::AssertIOAllowed();
904 // Windows compatibility: if to_path exists, from_path and to_path
905 // must be the same type, either both files, or both directories.
906 stat_wrapper_t to_file_info;
907 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
908 stat_wrapper_t from_file_info;
909 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
910 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
911 return false;
912 } else {
913 return false;
914 }
915 }
916
917 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
918 return true;
919
920 if (!CopyDirectory(from_path, to_path, true))
921 return false;
922
[email protected]dd3aa792013-07-16 19:10:23923 DeleteFile(from_path, true);
[email protected]f0ff2ad2013-07-09 17:42:26924 return true;
925}
926
927#if !defined(OS_MACOSX)
928// Mac has its own implementation, this is for all other Posix systems.
929bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
930 ThreadRestrictions::AssertIOAllowed();
931 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
932 if (infile < 0)
933 return false;
934
935 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
936 if (outfile < 0) {
[email protected]d89eec82013-12-03 14:10:59937 close(infile);
[email protected]f0ff2ad2013-07-09 17:42:26938 return false;
939 }
940
941 const size_t kBufferSize = 32768;
942 std::vector<char> buffer(kBufferSize);
943 bool result = true;
944
945 while (result) {
946 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
947 if (bytes_read < 0) {
948 result = false;
949 break;
950 }
951 if (bytes_read == 0)
952 break;
953 // Allow for partial writes
954 ssize_t bytes_written_per_read = 0;
955 do {
956 ssize_t bytes_written_partial = HANDLE_EINTR(write(
957 outfile,
958 &buffer[bytes_written_per_read],
959 bytes_read - bytes_written_per_read));
960 if (bytes_written_partial < 0) {
961 result = false;
962 break;
963 }
964 bytes_written_per_read += bytes_written_partial;
965 } while (bytes_written_per_read < bytes_read);
966 }
967
[email protected]d89eec82013-12-03 14:10:59968 if (IGNORE_EINTR(close(infile)) < 0)
[email protected]f0ff2ad2013-07-09 17:42:26969 result = false;
[email protected]d89eec82013-12-03 14:10:59970 if (IGNORE_EINTR(close(outfile)) < 0)
[email protected]f0ff2ad2013-07-09 17:42:26971 result = false;
972
973 return result;
974}
975#endif // !defined(OS_MACOSX)
976
977} // namespace internal
978} // namespace base