blob: 762700ae42c11d42e39bffaf89aaf4472a704dd9 [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]f7d69972011-06-21 22:34:5027#elif !defined(OS_ANDROID)
[email protected]1c657852010-04-22 23:28:0528#include <glib.h>
[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]34b99632011-01-01 01:01:0646#include "base/threading/thread_restrictions.h"
[email protected]99084f62013-06-28 00:49:0747#include "base/time/time.h"
[email protected]172c5502009-06-24 03:29:2648
[email protected]f7d69972011-06-21 22:34:5049#if defined(OS_ANDROID)
50#include "base/os_compat_android.h"
51#endif
52
[email protected]4bd46792012-07-09 14:40:3953#if !defined(OS_IOS)
54#include <grp.h>
55#endif
56
[email protected]774727282012-08-06 09:14:4457#if defined(OS_CHROMEOS)
58#include "base/chromeos/chromeos_version.h"
59#endif
60
[email protected]15476932013-04-12 05:17:1561namespace base {
62
[email protected]6f5f4322010-06-09 22:56:4863namespace {
64
[email protected]07a35222012-07-19 22:24:0265#if defined(OS_BSD) || defined(OS_MACOSX)
[email protected]73e4c362011-09-22 14:47:1866typedef struct stat stat_wrapper_t;
67static int CallStat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3668 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1869 return stat(path, sb);
70}
71static int CallLstat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3672 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1873 return lstat(path, sb);
74}
75#else
76typedef struct stat64 stat_wrapper_t;
77static int CallStat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3678 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1879 return stat64(path, sb);
80}
81static int CallLstat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3682 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1883 return lstat64(path, sb);
84}
85#endif
86
[email protected]6f5f4322010-06-09 22:56:4887// Helper for NormalizeFilePath(), defined below.
88bool RealPath(const FilePath& path, FilePath* real_path) {
[email protected]5553d5b2013-07-01 23:07:3689 ThreadRestrictions::AssertIOAllowed(); // For realpath().
[email protected]6f5f4322010-06-09 22:56:4890 FilePath::CharType buf[PATH_MAX];
91 if (!realpath(path.value().c_str(), buf))
92 return false;
93
94 *real_path = FilePath(buf);
95 return true;
96}
97
[email protected]73e4c362011-09-22 14:47:1898// Helper for VerifyPathControlledByUser.
99bool VerifySpecificPathControlledByUser(const FilePath& path,
100 uid_t owner_uid,
[email protected]7312f42a2011-10-17 21:30:29101 const std::set<gid_t>& group_gids) {
[email protected]73e4c362011-09-22 14:47:18102 stat_wrapper_t stat_info;
103 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
[email protected]a42d4632011-10-26 21:48:00104 DPLOG(ERROR) << "Failed to get information on path "
105 << path.value();
[email protected]73e4c362011-09-22 14:47:18106 return false;
107 }
[email protected]6f5f4322010-06-09 22:56:48108
[email protected]73e4c362011-09-22 14:47:18109 if (S_ISLNK(stat_info.st_mode)) {
[email protected]a42d4632011-10-26 21:48:00110 DLOG(ERROR) << "Path " << path.value()
[email protected]73e4c362011-09-22 14:47:18111 << " is a symbolic link.";
112 return false;
113 }
114
115 if (stat_info.st_uid != owner_uid) {
[email protected]a42d4632011-10-26 21:48:00116 DLOG(ERROR) << "Path " << path.value()
117 << " is owned by the wrong user.";
[email protected]73e4c362011-09-22 14:47:18118 return false;
119 }
120
[email protected]7312f42a2011-10-17 21:30:29121 if ((stat_info.st_mode & S_IWGRP) &&
122 !ContainsKey(group_gids, stat_info.st_gid)) {
[email protected]a42d4632011-10-26 21:48:00123 DLOG(ERROR) << "Path " << path.value()
124 << " is writable by an unprivileged group.";
[email protected]73e4c362011-09-22 14:47:18125 return false;
126 }
127
128 if (stat_info.st_mode & S_IWOTH) {
[email protected]a42d4632011-10-26 21:48:00129 DLOG(ERROR) << "Path " << path.value()
130 << " is writable by any user.";
[email protected]73e4c362011-09-22 14:47:18131 return false;
132 }
133
134 return true;
[email protected]fb66f9d2009-09-07 16:39:46135}
[email protected]73e4c362011-09-22 14:47:18136
[email protected]5553d5b2013-07-01 23:07:36137std::string TempFileName() {
138#if defined(OS_MACOSX)
139 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
140#endif
141
142#if defined(GOOGLE_CHROME_BUILD)
143 return std::string(".com.google.Chrome.XXXXXX");
144#else
145 return std::string(".org.chromium.Chromium.XXXXXX");
146#endif
147}
148
[email protected]73e4c362011-09-22 14:47:18149} // namespace
[email protected]fb66f9d2009-09-07 16:39:46150
[email protected]918efbf2013-07-01 19:41:02151FilePath MakeAbsoluteFilePath(const FilePath& input) {
152 ThreadRestrictions::AssertIOAllowed();
153 char full_path[PATH_MAX];
154 if (realpath(input.value().c_str(), full_path) == NULL)
155 return FilePath();
156 return FilePath(full_path);
[email protected]151c4a62011-04-22 04:15:13157}
[email protected]778e8c52008-09-11 17:36:23158
[email protected]b2e97292008-09-02 18:20:34159// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
160// which works both with and without the recursive flag. I'm not sure we need
161// that functionality. If not, remove from file_util_win.cc, otherwise add it
162// here.
[email protected]dd3aa792013-07-16 19:10:23163bool DeleteFile(const FilePath& path, bool recursive) {
[email protected]918efbf2013-07-01 19:41:02164 ThreadRestrictions::AssertIOAllowed();
[email protected]640517f2008-10-30 23:54:04165 const char* path_str = path.value().c_str();
[email protected]fb66f9d2009-09-07 16:39:46166 stat_wrapper_t file_info;
[email protected]7122db22012-06-30 05:26:59167 int test = CallLstat(path_str, &file_info);
[email protected]b2e97292008-09-02 18:20:34168 if (test != 0) {
169 // The Windows version defines this condition as success.
[email protected]9e51af92009-02-04 00:58:39170 bool ret = (errno == ENOENT || errno == ENOTDIR);
[email protected]b2e97292008-09-02 18:20:34171 return ret;
172 }
173 if (!S_ISDIR(file_info.st_mode))
[email protected]640517f2008-10-30 23:54:04174 return (unlink(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34175 if (!recursive)
[email protected]640517f2008-10-30 23:54:04176 return (rmdir(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34177
178 bool success = true;
[email protected]49930c3a2009-08-06 21:23:07179 std::stack<std::string> directories;
180 directories.push(path.value());
[email protected]84c3f162012-08-12 01:57:23181 FileEnumerator traversal(path, true,
182 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
183 FileEnumerator::SHOW_SYM_LINKS);
[email protected]49930c3a2009-08-06 21:23:07184 for (FilePath current = traversal.Next(); success && !current.empty();
185 current = traversal.Next()) {
[email protected]25a4c1c2013-06-08 04:53:36186 if (traversal.GetInfo().IsDirectory())
[email protected]49930c3a2009-08-06 21:23:07187 directories.push(current.value());
188 else
189 success = (unlink(current.value().c_str()) == 0);
[email protected]21dec3872008-09-18 19:15:54190 }
[email protected]49930c3a2009-08-06 21:23:07191
192 while (success && !directories.empty()) {
193 FilePath dir = FilePath(directories.top());
194 directories.pop();
195 success = (rmdir(dir.value().c_str()) == 0);
[email protected]b2e97292008-09-02 18:20:34196 }
197 return success;
198}
199
[email protected]5553d5b2013-07-01 23:07:36200bool ReplaceFile(const FilePath& from_path,
201 const FilePath& to_path,
202 PlatformFileError* error) {
203 ThreadRestrictions::AssertIOAllowed();
[email protected]6f5399412013-05-08 22:02:36204 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
205 return true;
206 if (error)
[email protected]5553d5b2013-07-01 23:07:36207 *error = ErrnoToPlatformFileError(errno);
[email protected]6f5399412013-05-08 22:02:36208 return false;
[email protected]c5866dca2009-05-19 17:21:07209}
210
[email protected]9e66a9b2013-05-08 05:46:20211bool CopyDirectory(const FilePath& from_path,
212 const FilePath& to_path,
[email protected]21dec3872008-09-18 19:15:54213 bool recursive) {
[email protected]f0ff2ad2013-07-09 17:42:26214 ThreadRestrictions::AssertIOAllowed();
[email protected]21dec3872008-09-18 19:15:54215 // Some old callers of CopyDirectory want it to support wildcards.
216 // After some discussion, we decided to fix those callers.
217 // Break loudly here if anyone tries to do this.
[email protected]9e66a9b2013-05-08 05:46:20218 // TODO(evanm): remove this once we're sure it's ok.
[email protected]640517f2008-10-30 23:54:04219 DCHECK(to_path.value().find('*') == std::string::npos);
220 DCHECK(from_path.value().find('*') == std::string::npos);
[email protected]21dec3872008-09-18 19:15:54221
222 char top_dir[PATH_MAX];
[email protected]f0ff2ad2013-07-09 17:42:26223 if (strlcpy(top_dir, from_path.value().c_str(),
224 arraysize(top_dir)) >= arraysize(top_dir)) {
[email protected]21dec3872008-09-18 19:15:54225 return false;
226 }
227
[email protected]49930c3a2009-08-06 21:23:07228 // This function does not properly handle destinations within the source
229 FilePath real_to_path = to_path;
[email protected]7567484142013-07-11 17:36:07230 if (PathExists(real_to_path)) {
[email protected]15476932013-04-12 05:17:15231 real_to_path = MakeAbsoluteFilePath(real_to_path);
232 if (real_to_path.empty())
[email protected]49930c3a2009-08-06 21:23:07233 return false;
234 } else {
[email protected]15476932013-04-12 05:17:15235 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
236 if (real_to_path.empty())
[email protected]49930c3a2009-08-06 21:23:07237 return false;
238 }
[email protected]15476932013-04-12 05:17:15239 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
240 if (real_from_path.empty())
[email protected]21dec3872008-09-18 19:15:54241 return false;
[email protected]49930c3a2009-08-06 21:23:07242 if (real_to_path.value().size() >= real_from_path.value().size() &&
243 real_to_path.value().compare(0, real_from_path.value().size(),
244 real_from_path.value()) == 0)
245 return false;
246
247 bool success = true;
[email protected]84c3f162012-08-12 01:57:23248 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
[email protected]49930c3a2009-08-06 21:23:07249 if (recursive)
[email protected]84c3f162012-08-12 01:57:23250 traverse_type |= FileEnumerator::DIRECTORIES;
[email protected]49930c3a2009-08-06 21:23:07251 FileEnumerator traversal(from_path, recursive, traverse_type);
252
[email protected]abbc5732009-10-13 17:57:27253 // We have to mimic windows behavior here. |to_path| may not exist yet,
[email protected]bc6a9012009-10-15 01:11:44254 // start the loop with |to_path|.
[email protected]25a4c1c2013-06-08 04:53:36255 struct stat from_stat;
[email protected]49930c3a2009-08-06 21:23:07256 FilePath current = from_path;
[email protected]25a4c1c2013-06-08 04:53:36257 if (stat(from_path.value().c_str(), &from_stat) < 0) {
[email protected]a42d4632011-10-26 21:48:00258 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
259 << from_path.value() << " errno = " << errno;
[email protected]49930c3a2009-08-06 21:23:07260 success = false;
[email protected]21dec3872008-09-18 19:15:54261 }
[email protected]bc6a9012009-10-15 01:11:44262 struct stat to_path_stat;
263 FilePath from_path_base = from_path;
264 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
265 S_ISDIR(to_path_stat.st_mode)) {
266 // If the destination already exists and is a directory, then the
267 // top level of source needs to be copied.
268 from_path_base = from_path.DirName();
269 }
270
271 // The Windows version of this function assumes that non-recursive calls
272 // will always have a directory for from_path.
[email protected]25a4c1c2013-06-08 04:53:36273 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
[email protected]21dec3872008-09-18 19:15:54274
[email protected]49930c3a2009-08-06 21:23:07275 while (success && !current.empty()) {
[email protected]92e06492013-01-30 11:38:02276 // current is the source path, including from_path, so append
277 // the suffix after from_path to to_path to create the target_path.
278 FilePath target_path(to_path);
279 if (from_path_base != current) {
280 if (!from_path_base.AppendRelativePath(current, &target_path)) {
281 success = false;
282 break;
283 }
[email protected]ca0209612009-01-13 18:57:46284 }
[email protected]21dec3872008-09-18 19:15:54285
[email protected]25a4c1c2013-06-08 04:53:36286 if (S_ISDIR(from_stat.st_mode)) {
287 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
[email protected]49930c3a2009-08-06 21:23:07288 errno != EEXIST) {
[email protected]a42d4632011-10-26 21:48:00289 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
290 << target_path.value() << " errno = " << errno;
[email protected]49930c3a2009-08-06 21:23:07291 success = false;
292 }
[email protected]25a4c1c2013-06-08 04:53:36293 } else if (S_ISREG(from_stat.st_mode)) {
[email protected]49930c3a2009-08-06 21:23:07294 if (!CopyFile(current, target_path)) {
[email protected]a42d4632011-10-26 21:48:00295 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
296 << target_path.value();
[email protected]49930c3a2009-08-06 21:23:07297 success = false;
298 }
299 } else {
[email protected]a42d4632011-10-26 21:48:00300 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
301 << current.value();
[email protected]21dec3872008-09-18 19:15:54302 }
[email protected]21dec3872008-09-18 19:15:54303
[email protected]49930c3a2009-08-06 21:23:07304 current = traversal.Next();
[email protected]25a4c1c2013-06-08 04:53:36305 if (!current.empty())
306 from_stat = traversal.GetInfo().stat();
[email protected]21dec3872008-09-18 19:15:54307 }
308
[email protected]49930c3a2009-08-06 21:23:07309 return success;
[email protected]b2e97292008-09-02 18:20:34310}
311
[email protected]7567484142013-07-11 17:36:07312bool PathExists(const FilePath& path) {
313 ThreadRestrictions::AssertIOAllowed();
314 return access(path.value().c_str(), F_OK) == 0;
315}
316
[email protected]dcd16612013-07-15 20:18:09317bool PathIsWritable(const FilePath& path) {
318 ThreadRestrictions::AssertIOAllowed();
319 return access(path.value().c_str(), W_OK) == 0;
320}
321
322bool DirectoryExists(const FilePath& path) {
323 ThreadRestrictions::AssertIOAllowed();
324 stat_wrapper_t file_info;
325 if (CallStat(path.value().c_str(), &file_info) == 0)
326 return S_ISDIR(file_info.st_mode);
327 return false;
328}
329
[email protected]f0ff2ad2013-07-09 17:42:26330} // namespace base
331
332// -----------------------------------------------------------------------------
333
334namespace file_util {
335
336using base::stat_wrapper_t;
337using base::CallStat;
338using base::CallLstat;
[email protected]dcd16612013-07-15 20:18:09339using base::DirectoryExists;
[email protected]f0ff2ad2013-07-09 17:42:26340using base::FileEnumerator;
341using base::FilePath;
342using base::MakeAbsoluteFilePath;
343using base::RealPath;
344using base::VerifySpecificPathControlledByUser;
345
[email protected]45301492009-04-23 12:38:08346bool ReadFromFD(int fd, char* buffer, size_t bytes) {
347 size_t total_read = 0;
348 while (total_read < bytes) {
[email protected]157c61b2009-05-01 21:37:31349 ssize_t bytes_read =
350 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
351 if (bytes_read <= 0)
[email protected]45301492009-04-23 12:38:08352 break;
[email protected]157c61b2009-05-01 21:37:31353 total_read += bytes_read;
[email protected]45301492009-04-23 12:38:08354 }
355 return total_read == bytes;
356}
357
[email protected]2e733d102010-11-30 00:43:37358bool CreateSymbolicLink(const FilePath& target_path,
359 const FilePath& symlink_path) {
360 DCHECK(!symlink_path.empty());
361 DCHECK(!target_path.empty());
362 return ::symlink(target_path.value().c_str(),
363 symlink_path.value().c_str()) != -1;
364}
365
366bool ReadSymbolicLink(const FilePath& symlink_path,
367 FilePath* target_path) {
368 DCHECK(!symlink_path.empty());
369 DCHECK(target_path);
370 char buf[PATH_MAX];
371 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
372
[email protected]723571a2010-12-03 17:37:54373 if (count <= 0) {
374 target_path->clear();
[email protected]2e733d102010-11-30 00:43:37375 return false;
[email protected]723571a2010-12-03 17:37:54376 }
[email protected]2e733d102010-11-30 00:43:37377
378 *target_path = FilePath(FilePath::StringType(buf, count));
[email protected]2e733d102010-11-30 00:43:37379 return true;
380}
381
[email protected]5085e442012-07-11 01:24:02382bool GetPosixFilePermissions(const FilePath& path, int* mode) {
383 base::ThreadRestrictions::AssertIOAllowed();
384 DCHECK(mode);
385
386 stat_wrapper_t file_info;
387 // Uses stat(), because on symbolic link, lstat() does not return valid
388 // permission bits in st_mode
389 if (CallStat(path.value().c_str(), &file_info) != 0)
390 return false;
391
392 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
393 return true;
394}
395
396bool SetPosixFilePermissions(const FilePath& path,
397 int mode) {
398 base::ThreadRestrictions::AssertIOAllowed();
399 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
400
401 // Calls stat() so that we can preserve the higher bits like S_ISGID.
402 stat_wrapper_t stat_buf;
403 if (CallStat(path.value().c_str(), &stat_buf) != 0)
404 return false;
405
406 // Clears the existing permission bits, and adds the new ones.
407 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
408 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
409
410 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
411 return false;
412
413 return true;
414}
415
[email protected]9e51af92009-02-04 00:58:39416// Creates and opens a temporary file in |directory|, returning the
[email protected]16eac0a72009-09-11 17:33:50417// file descriptor. |path| is set to the temporary file path.
418// This function does NOT unlink() the file.
[email protected]9e51af92009-02-04 00:58:39419int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
[email protected]ba74b0d22010-10-23 05:19:20420 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
[email protected]5553d5b2013-07-01 23:07:36421 *path = directory.Append(base::TempFileName());
[email protected]9e51af92009-02-04 00:58:39422 const std::string& tmpdir_string = path->value();
[email protected]778e8c52008-09-11 17:36:23423 // this should be OK since mkstemp just replaces characters in place
424 char* buffer = const_cast<char*>(tmpdir_string.c_str());
[email protected]392264c2008-11-11 00:01:38425
[email protected]b266ffea2011-04-12 06:07:25426 return HANDLE_EINTR(mkstemp(buffer));
[email protected]9e51af92009-02-04 00:58:39427}
428
[email protected]33edeab2009-08-18 16:07:55429bool CreateTemporaryFile(FilePath* path) {
[email protected]ba74b0d22010-10-23 05:19:20430 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]9e51af92009-02-04 00:58:39431 FilePath directory;
432 if (!GetTempDir(&directory))
433 return false;
434 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
[email protected]b2e97292008-09-02 18:20:34435 if (fd < 0)
436 return false;
[email protected]2e90bee2011-04-12 06:51:22437 ignore_result(HANDLE_EINTR(close(fd)));
[email protected]b2e97292008-09-02 18:20:34438 return true;
439}
440
[email protected]103dccfa2011-12-06 18:07:05441FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
[email protected]9e51af92009-02-04 00:58:39442 FilePath directory;
[email protected]103dccfa2011-12-06 18:07:05443 if (!GetShmemTempDir(&directory, executable))
[email protected]628476aa2010-06-10 22:56:23444 return NULL;
[email protected]9e51af92009-02-04 00:58:39445
[email protected]6faa0e0d2009-04-28 06:50:36446 return CreateAndOpenTemporaryFileInDir(directory, path);
447}
448
449FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
450 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
[email protected]9e51af92009-02-04 00:58:39451 if (fd < 0)
452 return NULL;
453
[email protected]139063bd2011-04-18 19:05:53454 FILE* file = fdopen(fd, "a+");
455 if (!file)
456 ignore_result(HANDLE_EINTR(close(fd)));
457 return file;
[email protected]9e51af92009-02-04 00:58:39458}
[email protected]6445c402009-09-11 20:06:27459
460bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
[email protected]ba74b0d22010-10-23 05:19:20461 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]6445c402009-09-11 20:06:27462 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
[email protected]b266ffea2011-04-12 06:07:25463 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
[email protected]9ccbb372008-10-10 18:50:32464}
465
[email protected]b0b3abd92010-04-30 17:00:09466static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
467 const FilePath::StringType& name_tmpl,
468 FilePath* new_dir) {
[email protected]ba74b0d22010-10-23 05:19:20469 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
[email protected]a42d4632011-10-26 21:48:00470 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
471 << "Directory name template must contain \"XXXXXX\".";
[email protected]b0b3abd92010-04-30 17:00:09472
473 FilePath sub_dir = base_dir.Append(name_tmpl);
474 std::string sub_dir_string = sub_dir.value();
475
476 // this should be OK since mkdtemp just replaces characters in place
477 char* buffer = const_cast<char*>(sub_dir_string.c_str());
478 char* dtemp = mkdtemp(buffer);
[email protected]3ad035d22010-07-28 21:00:51479 if (!dtemp) {
480 DPLOG(ERROR) << "mkdtemp";
[email protected]b0b3abd92010-04-30 17:00:09481 return false;
[email protected]3ad035d22010-07-28 21:00:51482 }
[email protected]b0b3abd92010-04-30 17:00:09483 *new_dir = FilePath(dtemp);
484 return true;
485}
486
487bool CreateTemporaryDirInDir(const FilePath& base_dir,
488 const FilePath::StringType& prefix,
[email protected]046062e82010-06-30 07:19:11489 FilePath* new_dir) {
[email protected]b0b3abd92010-04-30 17:00:09490 FilePath::StringType mkdtemp_template = prefix;
491 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
492 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
493}
494
[email protected]7e1fde6a2008-12-23 20:20:10495bool CreateNewTempDirectory(const FilePath::StringType& prefix,
496 FilePath* new_temp_path) {
[email protected]392264c2008-11-11 00:01:38497 FilePath tmpdir;
[email protected]b2e97292008-09-02 18:20:34498 if (!GetTempDir(&tmpdir))
499 return false;
[email protected]b0b3abd92010-04-30 17:00:09500
[email protected]5553d5b2013-07-01 23:07:36501 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
502 new_temp_path);
[email protected]b2e97292008-09-02 18:20:34503}
504
[email protected]cfd23d22013-06-11 03:50:25505bool CreateDirectoryAndGetError(const FilePath& full_path,
506 base::PlatformFileError* error) {
[email protected]ba74b0d22010-10-23 05:19:20507 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
[email protected]640517f2008-10-30 23:54:04508 std::vector<FilePath> subpaths;
509
510 // Collect a list of all parent directories.
511 FilePath last_path = full_path;
512 subpaths.push_back(full_path);
513 for (FilePath path = full_path.DirName();
514 path.value() != last_path.value(); path = path.DirName()) {
515 subpaths.push_back(path);
516 last_path = path;
517 }
518
519 // Iterate through the parents and create the missing ones.
520 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
521 i != subpaths.rend(); ++i) {
[email protected]0ba86e42010-03-17 21:39:42522 if (DirectoryExists(*i))
523 continue;
524 if (mkdir(i->value().c_str(), 0700) == 0)
525 continue;
526 // Mkdir failed, but it might have failed with EEXIST, or some other error
527 // due to the the directory appearing out of thin air. This can occur if
528 // two processes are trying to create the same file system tree at the same
529 // time. Check to see if it exists and make sure it is a directory.
[email protected]cfd23d22013-06-11 03:50:25530 int saved_errno = errno;
531 if (!DirectoryExists(*i)) {
532 if (error)
533 *error = base::ErrnoToPlatformFileError(saved_errno);
[email protected]0ba86e42010-03-17 21:39:42534 return false;
[email protected]cfd23d22013-06-11 03:50:25535 }
[email protected]b2e97292008-09-02 18:20:34536 }
537 return true;
538}
539
[email protected]992c73e2013-04-04 09:05:21540base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
541 const int kMaxAttempts = 20;
542 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
[email protected]007b3f82013-04-09 08:46:45543 int uniquifier =
544 GetUniquePathNumber(path, base::FilePath::StringType());
[email protected]992c73e2013-04-04 09:05:21545 if (uniquifier < 0)
546 break;
547 base::FilePath test_path = (uniquifier == 0) ? path :
548 path.InsertBeforeExtensionASCII(
549 base::StringPrintf(" (%d)", uniquifier));
550 if (mkdir(test_path.value().c_str(), 0777) == 0)
551 return test_path;
552 else if (errno != EEXIST)
553 break;
554 }
555 return base::FilePath();
556}
557
[email protected]cd78ad52011-05-31 23:10:06558// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
559// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
560bool IsLink(const FilePath& file_path) {
[email protected]7122db22012-06-30 05:26:59561 stat_wrapper_t st;
[email protected]cd78ad52011-05-31 23:10:06562 // If we can't lstat the file, it's safe to assume that the file won't at
563 // least be a 'followable' link.
[email protected]7122db22012-06-30 05:26:59564 if (CallLstat(file_path.value().c_str(), &st) != 0)
[email protected]cd78ad52011-05-31 23:10:06565 return false;
566
567 if (S_ISLNK(st.st_mode))
568 return true;
569 else
570 return false;
571}
572
[email protected]2f0193c22010-09-03 02:28:37573bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
[email protected]fb66f9d2009-09-07 16:39:46574 stat_wrapper_t file_info;
575 if (CallStat(file_path.value().c_str(), &file_info) != 0)
[email protected]b2e97292008-09-02 18:20:34576 return false;
[email protected]f5e3da4d2008-09-26 01:04:08577 results->is_directory = S_ISDIR(file_info.st_mode);
578 results->size = file_info.st_size;
[email protected]92bb9cb2013-06-10 09:41:35579#if defined(OS_MACOSX)
580 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
581 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
582 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
583#elif defined(OS_ANDROID)
[email protected]5ef323892009-07-24 16:13:53584 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
[email protected]2f0193c22010-09-03 02:28:37585 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
586 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
[email protected]92bb9cb2013-06-10 09:41:35587#else
588 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
589 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
590 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
591#endif
[email protected]b2e97292008-09-02 18:20:34592 return true;
593}
594
[email protected]825003f2009-05-14 17:49:23595bool GetInode(const FilePath& path, ino_t* inode) {
[email protected]ba74b0d22010-10-23 05:19:20596 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
[email protected]825003f2009-05-14 17:49:23597 struct stat buffer;
598 int result = stat(path.value().c_str(), &buffer);
599 if (result < 0)
600 return false;
601
602 *inode = buffer.st_ino;
603 return true;
604}
605
[email protected]836f1342008-10-01 17:40:13606FILE* OpenFile(const std::string& filename, const char* mode) {
[email protected]a9cd2a652008-11-17 21:01:19607 return OpenFile(FilePath(filename), mode);
[email protected]836f1342008-10-01 17:40:13608}
609
[email protected]a9cd2a652008-11-17 21:01:19610FILE* OpenFile(const FilePath& filename, const char* mode) {
[email protected]ba74b0d22010-10-23 05:19:20611 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25612 FILE* result = NULL;
613 do {
614 result = fopen(filename.value().c_str(), mode);
615 } while (!result && errno == EINTR);
616 return result;
[email protected]836f1342008-10-01 17:40:13617}
618
[email protected]c870c762009-01-28 05:47:15619int ReadFile(const FilePath& filename, char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20620 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25621 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
[email protected]b2e97292008-09-02 18:20:34622 if (fd < 0)
623 return -1;
[email protected]a9cd2a652008-11-17 21:01:19624
[email protected]cabe39c2010-02-02 02:28:16625 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
626 if (int ret = HANDLE_EINTR(close(fd)) < 0)
627 return ret;
628 return bytes_read;
[email protected]b2e97292008-09-02 18:20:34629}
630
[email protected]c870c762009-01-28 05:47:15631int WriteFile(const FilePath& filename, const char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20632 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25633 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
[email protected]b2e97292008-09-02 18:20:34634 if (fd < 0)
635 return -1;
[email protected]778e8c52008-09-11 17:36:23636
[email protected]cabe39c2010-02-02 02:28:16637 int bytes_written = WriteFileDescriptor(fd, data, size);
638 if (int ret = HANDLE_EINTR(close(fd)) < 0)
639 return ret;
640 return bytes_written;
[email protected]fbea0232009-09-16 00:29:22641}
642
643int WriteFileDescriptor(const int fd, const char* data, int size) {
644 // Allow for partial writes.
645 ssize_t bytes_written_total = 0;
646 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
647 bytes_written_total += bytes_written_partial) {
648 bytes_written_partial =
649 HANDLE_EINTR(write(fd, data + bytes_written_total,
650 size - bytes_written_total));
651 if (bytes_written_partial < 0)
652 return -1;
653 }
654
[email protected]778e8c52008-09-11 17:36:23655 return bytes_written_total;
[email protected]b2e97292008-09-02 18:20:34656}
657
[email protected]891128f2012-04-29 12:57:10658int AppendToFile(const FilePath& filename, const char* data, int size) {
659 base::ThreadRestrictions::AssertIOAllowed();
660 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
661 if (fd < 0)
662 return -1;
663
664 int bytes_written = WriteFileDescriptor(fd, data, size);
665 if (int ret = HANDLE_EINTR(close(fd)) < 0)
666 return ret;
667 return bytes_written;
668}
669
[email protected]b2e97292008-09-02 18:20:34670// Gets the current working directory for the process.
[email protected]640517f2008-10-30 23:54:04671bool GetCurrentDirectory(FilePath* dir) {
[email protected]ba74b0d22010-10-23 05:19:20672 // getcwd can return ENOENT, which implies it checks against the disk.
673 base::ThreadRestrictions::AssertIOAllowed();
674
[email protected]b2e97292008-09-02 18:20:34675 char system_buffer[PATH_MAX] = "";
[email protected]640517f2008-10-30 23:54:04676 if (!getcwd(system_buffer, sizeof(system_buffer))) {
677 NOTREACHED();
678 return false;
679 }
680 *dir = FilePath(system_buffer);
[email protected]b2e97292008-09-02 18:20:34681 return true;
682}
683
684// Sets the current working directory for the process.
[email protected]a9cd2a652008-11-17 21:01:19685bool SetCurrentDirectory(const FilePath& path) {
[email protected]ba74b0d22010-10-23 05:19:20686 base::ThreadRestrictions::AssertIOAllowed();
[email protected]a9cd2a652008-11-17 21:01:19687 int ret = chdir(path.value().c_str());
688 return !ret;
[email protected]b2e97292008-09-02 18:20:34689}
[email protected]a9cd2a652008-11-17 21:01:19690
[email protected]6f5f4322010-06-09 22:56:48691bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
692 FilePath real_path_result;
693 if (!RealPath(path, &real_path_result))
[email protected]01e2a1f2010-05-12 15:13:57694 return false;
695
[email protected]6f5f4322010-06-09 22:56:48696 // To be consistant with windows, fail if |real_path_result| is a
697 // directory.
698 stat_wrapper_t file_info;
699 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
700 S_ISDIR(file_info.st_mode))
701 return false;
702
703 *normalized_path = real_path_result;
[email protected]01e2a1f2010-05-12 15:13:57704 return true;
705}
706
[email protected]84cb1912010-04-21 21:11:36707#if !defined(OS_MACOSX)
708bool GetTempDir(FilePath* path) {
709 const char* tmp = getenv("TMPDIR");
710 if (tmp)
711 *path = FilePath(tmp);
712 else
[email protected]f7d69972011-06-21 22:34:50713#if defined(OS_ANDROID)
[email protected]0eae7eb2012-05-17 20:09:06714 return PathService::Get(base::DIR_CACHE, path);
[email protected]f7d69972011-06-21 22:34:50715#else
[email protected]84cb1912010-04-21 21:11:36716 *path = FilePath("/tmp");
[email protected]f7d69972011-06-21 22:34:50717#endif
[email protected]84cb1912010-04-21 21:11:36718 return true;
719}
720
[email protected]f7d69972011-06-21 22:34:50721#if !defined(OS_ANDROID)
[email protected]103dccfa2011-12-06 18:07:05722
[email protected]167ec822011-10-24 22:05:27723#if defined(OS_LINUX)
[email protected]103dccfa2011-12-06 18:07:05724// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
725// This depends on the mount options used for /dev/shm, which vary among
726// different Linux distributions and possibly local configuration. It also
727// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
728// but its kernel allows mprotect with PROT_EXEC anyway.
729
730namespace {
731
732bool DetermineDevShmExecutable() {
733 bool result = false;
734 FilePath path;
735 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
736 if (fd >= 0) {
737 ScopedFD shm_fd_closer(&fd);
[email protected]dd3aa792013-07-16 19:10:23738 DeleteFile(path, false);
[email protected]37e77e02011-12-22 22:31:44739 long sysconf_result = sysconf(_SC_PAGESIZE);
740 CHECK_GE(sysconf_result, 0);
741 size_t pagesize = static_cast<size_t>(sysconf_result);
742 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
[email protected]103dccfa2011-12-06 18:07:05743 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
744 if (mapping != MAP_FAILED) {
745 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
746 result = true;
747 munmap(mapping, pagesize);
748 }
749 }
750 return result;
[email protected]84cb1912010-04-21 21:11:36751}
[email protected]103dccfa2011-12-06 18:07:05752
753}; // namespace
754#endif // defined(OS_LINUX)
755
756bool GetShmemTempDir(FilePath* path, bool executable) {
757#if defined(OS_LINUX)
758 bool use_dev_shm = true;
759 if (executable) {
760 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
761 use_dev_shm = s_dev_shm_executable;
762 }
763 if (use_dev_shm) {
764 *path = FilePath("/dev/shm");
765 return true;
766 }
[email protected]f7d69972011-06-21 22:34:50767#endif
[email protected]103dccfa2011-12-06 18:07:05768 return GetTempDir(path);
769}
770#endif // !defined(OS_ANDROID)
[email protected]84cb1912010-04-21 21:11:36771
[email protected]1c657852010-04-22 23:28:05772FilePath GetHomeDir() {
[email protected]774727282012-08-06 09:14:44773#if defined(OS_CHROMEOS)
774 if (base::chromeos::IsRunningOnChromeOS())
775 return FilePath("/home/chronos/user");
776#endif
777
[email protected]1c657852010-04-22 23:28:05778 const char* home_dir = getenv("HOME");
779 if (home_dir && home_dir[0])
780 return FilePath(home_dir);
781
[email protected]f7d69972011-06-21 22:34:50782#if defined(OS_ANDROID)
[email protected]a42d4632011-10-26 21:48:00783 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
[email protected]f7d69972011-06-21 22:34:50784#else
[email protected]ba74b0d22010-10-23 05:19:20785 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
786 base::ThreadRestrictions::AssertIOAllowed();
787
[email protected]1c657852010-04-22 23:28:05788 home_dir = g_get_home_dir();
789 if (home_dir && home_dir[0])
790 return FilePath(home_dir);
[email protected]f7d69972011-06-21 22:34:50791#endif
[email protected]1c657852010-04-22 23:28:05792
793 FilePath rv;
794 if (file_util::GetTempDir(&rv))
795 return rv;
796
797 // Last resort.
798 return FilePath("/tmp");
799}
[email protected]92e44ae0a2012-07-23 08:22:44800#endif // !defined(OS_MACOSX)
[email protected]84cb1912010-04-21 21:11:36801
[email protected]73e4c362011-09-22 14:47:18802bool VerifyPathControlledByUser(const FilePath& base,
803 const FilePath& path,
804 uid_t owner_uid,
[email protected]7312f42a2011-10-17 21:30:29805 const std::set<gid_t>& group_gids) {
[email protected]73e4c362011-09-22 14:47:18806 if (base != path && !base.IsParent(path)) {
[email protected]a42d4632011-10-26 21:48:00807 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
808 << base.value() << "\", path = \"" << path.value() << "\"";
[email protected]73e4c362011-09-22 14:47:18809 return false;
810 }
811
812 std::vector<FilePath::StringType> base_components;
813 std::vector<FilePath::StringType> path_components;
814
815 base.GetComponents(&base_components);
816 path.GetComponents(&path_components);
817
818 std::vector<FilePath::StringType>::const_iterator ib, ip;
819 for (ib = base_components.begin(), ip = path_components.begin();
820 ib != base_components.end(); ++ib, ++ip) {
821 // |base| must be a subpath of |path|, so all components should match.
822 // If these CHECKs fail, look at the test that base is a parent of
823 // path at the top of this function.
[email protected]a42d4632011-10-26 21:48:00824 DCHECK(ip != path_components.end());
825 DCHECK(*ip == *ib);
[email protected]73e4c362011-09-22 14:47:18826 }
827
828 FilePath current_path = base;
[email protected]7312f42a2011-10-17 21:30:29829 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
[email protected]73e4c362011-09-22 14:47:18830 return false;
831
832 for (; ip != path_components.end(); ++ip) {
833 current_path = current_path.Append(*ip);
[email protected]7312f42a2011-10-17 21:30:29834 if (!VerifySpecificPathControlledByUser(
835 current_path, owner_uid, group_gids))
[email protected]73e4c362011-09-22 14:47:18836 return false;
837 }
838 return true;
839}
840
[email protected]4bd46792012-07-09 14:40:39841#if defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]73e4c362011-09-22 14:47:18842bool VerifyPathControlledByAdmin(const FilePath& path) {
843 const unsigned kRootUid = 0;
844 const FilePath kFileSystemRoot("/");
845
846 // The name of the administrator group on mac os.
[email protected]7312f42a2011-10-17 21:30:29847 const char* const kAdminGroupNames[] = {
848 "admin",
849 "wheel"
850 };
[email protected]73e4c362011-09-22 14:47:18851
852 // Reading the groups database may touch the file system.
853 base::ThreadRestrictions::AssertIOAllowed();
854
[email protected]7312f42a2011-10-17 21:30:29855 std::set<gid_t> allowed_group_ids;
856 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
857 struct group *group_record = getgrnam(kAdminGroupNames[i]);
858 if (!group_record) {
[email protected]a42d4632011-10-26 21:48:00859 DPLOG(ERROR) << "Could not get the group ID of group \""
860 << kAdminGroupNames[i] << "\".";
[email protected]7312f42a2011-10-17 21:30:29861 continue;
862 }
863
864 allowed_group_ids.insert(group_record->gr_gid);
[email protected]73e4c362011-09-22 14:47:18865 }
866
867 return VerifyPathControlledByUser(
[email protected]7312f42a2011-10-17 21:30:29868 kFileSystemRoot, path, kRootUid, allowed_group_ids);
[email protected]73e4c362011-09-22 14:47:18869}
[email protected]eba29932012-07-24 11:23:32870#endif // defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]73e4c362011-09-22 14:47:18871
[email protected]59480302013-02-21 03:24:08872int GetMaximumPathComponentLength(const FilePath& path) {
873 base::ThreadRestrictions::AssertIOAllowed();
874 return pathconf(path.value().c_str(), _PC_NAME_MAX);
875}
876
[email protected]33e585a2010-11-20 03:38:15877} // namespace file_util
[email protected]f0ff2ad2013-07-09 17:42:26878
879namespace base {
880namespace internal {
881
882bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
883 ThreadRestrictions::AssertIOAllowed();
884 // Windows compatibility: if to_path exists, from_path and to_path
885 // must be the same type, either both files, or both directories.
886 stat_wrapper_t to_file_info;
887 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
888 stat_wrapper_t from_file_info;
889 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
890 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
891 return false;
892 } else {
893 return false;
894 }
895 }
896
897 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
898 return true;
899
900 if (!CopyDirectory(from_path, to_path, true))
901 return false;
902
[email protected]dd3aa792013-07-16 19:10:23903 DeleteFile(from_path, true);
[email protected]f0ff2ad2013-07-09 17:42:26904 return true;
905}
906
907#if !defined(OS_MACOSX)
908// Mac has its own implementation, this is for all other Posix systems.
909bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
910 ThreadRestrictions::AssertIOAllowed();
911 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
912 if (infile < 0)
913 return false;
914
915 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
916 if (outfile < 0) {
917 ignore_result(HANDLE_EINTR(close(infile)));
918 return false;
919 }
920
921 const size_t kBufferSize = 32768;
922 std::vector<char> buffer(kBufferSize);
923 bool result = true;
924
925 while (result) {
926 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
927 if (bytes_read < 0) {
928 result = false;
929 break;
930 }
931 if (bytes_read == 0)
932 break;
933 // Allow for partial writes
934 ssize_t bytes_written_per_read = 0;
935 do {
936 ssize_t bytes_written_partial = HANDLE_EINTR(write(
937 outfile,
938 &buffer[bytes_written_per_read],
939 bytes_read - bytes_written_per_read));
940 if (bytes_written_partial < 0) {
941 result = false;
942 break;
943 }
944 bytes_written_per_read += bytes_written_partial;
945 } while (bytes_written_per_read < bytes_read);
946 }
947
948 if (HANDLE_EINTR(close(infile)) < 0)
949 result = false;
950 if (HANDLE_EINTR(close(outfile)) < 0)
951 result = false;
952
953 return result;
954}
955#endif // !defined(OS_MACOSX)
956
957} // namespace internal
958} // namespace base