blob: a2dd19b97c439bd9a406af09526b6b1947b4e726 [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]4ab65012013-11-07 11:38:3227#elif !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
28#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)
51#include "base/os_compat_android.h"
52#endif
53
[email protected]4bd46792012-07-09 14:40:3954#if !defined(OS_IOS)
55#include <grp.h>
56#endif
57
[email protected]15476932013-04-12 05:17:1558namespace base {
59
[email protected]6f5f4322010-06-09 22:56:4860namespace {
61
[email protected]07a35222012-07-19 22:24:0262#if defined(OS_BSD) || defined(OS_MACOSX)
[email protected]73e4c362011-09-22 14:47:1863typedef struct stat stat_wrapper_t;
64static int CallStat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3665 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1866 return stat(path, sb);
67}
68static int CallLstat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3669 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1870 return lstat(path, sb);
71}
72#else
73typedef struct stat64 stat_wrapper_t;
74static int CallStat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3675 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1876 return stat64(path, sb);
77}
78static int CallLstat(const char *path, stat_wrapper_t *sb) {
[email protected]5553d5b2013-07-01 23:07:3679 ThreadRestrictions::AssertIOAllowed();
[email protected]73e4c362011-09-22 14:47:1880 return lstat64(path, sb);
81}
82#endif
83
[email protected]6f5f4322010-06-09 22:56:4884// Helper for NormalizeFilePath(), defined below.
85bool RealPath(const FilePath& path, FilePath* real_path) {
[email protected]5553d5b2013-07-01 23:07:3686 ThreadRestrictions::AssertIOAllowed(); // For realpath().
[email protected]6f5f4322010-06-09 22:56:4887 FilePath::CharType buf[PATH_MAX];
88 if (!realpath(path.value().c_str(), buf))
89 return false;
90
91 *real_path = FilePath(buf);
92 return true;
93}
94
[email protected]73e4c362011-09-22 14:47:1895// Helper for VerifyPathControlledByUser.
96bool VerifySpecificPathControlledByUser(const FilePath& path,
97 uid_t owner_uid,
[email protected]7312f42a2011-10-17 21:30:2998 const std::set<gid_t>& group_gids) {
[email protected]73e4c362011-09-22 14:47:1899 stat_wrapper_t stat_info;
100 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
[email protected]a42d4632011-10-26 21:48:00101 DPLOG(ERROR) << "Failed to get information on path "
102 << path.value();
[email protected]73e4c362011-09-22 14:47:18103 return false;
104 }
[email protected]6f5f4322010-06-09 22:56:48105
[email protected]73e4c362011-09-22 14:47:18106 if (S_ISLNK(stat_info.st_mode)) {
[email protected]a42d4632011-10-26 21:48:00107 DLOG(ERROR) << "Path " << path.value()
[email protected]73e4c362011-09-22 14:47:18108 << " is a symbolic link.";
109 return false;
110 }
111
112 if (stat_info.st_uid != owner_uid) {
[email protected]a42d4632011-10-26 21:48:00113 DLOG(ERROR) << "Path " << path.value()
114 << " is owned by the wrong user.";
[email protected]73e4c362011-09-22 14:47:18115 return false;
116 }
117
[email protected]7312f42a2011-10-17 21:30:29118 if ((stat_info.st_mode & S_IWGRP) &&
119 !ContainsKey(group_gids, stat_info.st_gid)) {
[email protected]a42d4632011-10-26 21:48:00120 DLOG(ERROR) << "Path " << path.value()
121 << " is writable by an unprivileged group.";
[email protected]73e4c362011-09-22 14:47:18122 return false;
123 }
124
125 if (stat_info.st_mode & S_IWOTH) {
[email protected]a42d4632011-10-26 21:48:00126 DLOG(ERROR) << "Path " << path.value()
127 << " is writable by any user.";
[email protected]73e4c362011-09-22 14:47:18128 return false;
129 }
130
131 return true;
[email protected]fb66f9d2009-09-07 16:39:46132}
[email protected]73e4c362011-09-22 14:47:18133
[email protected]5553d5b2013-07-01 23:07:36134std::string TempFileName() {
135#if defined(OS_MACOSX)
136 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
137#endif
138
139#if defined(GOOGLE_CHROME_BUILD)
140 return std::string(".com.google.Chrome.XXXXXX");
141#else
142 return std::string(".org.chromium.Chromium.XXXXXX");
143#endif
144}
145
[email protected]73e4c362011-09-22 14:47:18146} // namespace
[email protected]fb66f9d2009-09-07 16:39:46147
[email protected]918efbf2013-07-01 19:41:02148FilePath MakeAbsoluteFilePath(const FilePath& input) {
149 ThreadRestrictions::AssertIOAllowed();
150 char full_path[PATH_MAX];
151 if (realpath(input.value().c_str(), full_path) == NULL)
152 return FilePath();
153 return FilePath(full_path);
[email protected]151c4a62011-04-22 04:15:13154}
[email protected]778e8c52008-09-11 17:36:23155
[email protected]b2e97292008-09-02 18:20:34156// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
157// which works both with and without the recursive flag. I'm not sure we need
158// that functionality. If not, remove from file_util_win.cc, otherwise add it
159// here.
[email protected]dd3aa792013-07-16 19:10:23160bool DeleteFile(const FilePath& path, bool recursive) {
[email protected]918efbf2013-07-01 19:41:02161 ThreadRestrictions::AssertIOAllowed();
[email protected]640517f2008-10-30 23:54:04162 const char* path_str = path.value().c_str();
[email protected]fb66f9d2009-09-07 16:39:46163 stat_wrapper_t file_info;
[email protected]7122db22012-06-30 05:26:59164 int test = CallLstat(path_str, &file_info);
[email protected]b2e97292008-09-02 18:20:34165 if (test != 0) {
166 // The Windows version defines this condition as success.
[email protected]9e51af92009-02-04 00:58:39167 bool ret = (errno == ENOENT || errno == ENOTDIR);
[email protected]b2e97292008-09-02 18:20:34168 return ret;
169 }
170 if (!S_ISDIR(file_info.st_mode))
[email protected]640517f2008-10-30 23:54:04171 return (unlink(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34172 if (!recursive)
[email protected]640517f2008-10-30 23:54:04173 return (rmdir(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34174
175 bool success = true;
[email protected]49930c3a2009-08-06 21:23:07176 std::stack<std::string> directories;
177 directories.push(path.value());
[email protected]84c3f162012-08-12 01:57:23178 FileEnumerator traversal(path, true,
179 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
180 FileEnumerator::SHOW_SYM_LINKS);
[email protected]49930c3a2009-08-06 21:23:07181 for (FilePath current = traversal.Next(); success && !current.empty();
182 current = traversal.Next()) {
[email protected]25a4c1c2013-06-08 04:53:36183 if (traversal.GetInfo().IsDirectory())
[email protected]49930c3a2009-08-06 21:23:07184 directories.push(current.value());
185 else
186 success = (unlink(current.value().c_str()) == 0);
[email protected]21dec3872008-09-18 19:15:54187 }
[email protected]49930c3a2009-08-06 21:23:07188
189 while (success && !directories.empty()) {
190 FilePath dir = FilePath(directories.top());
191 directories.pop();
192 success = (rmdir(dir.value().c_str()) == 0);
[email protected]b2e97292008-09-02 18:20:34193 }
194 return success;
195}
196
[email protected]5553d5b2013-07-01 23:07:36197bool ReplaceFile(const FilePath& from_path,
198 const FilePath& to_path,
199 PlatformFileError* error) {
200 ThreadRestrictions::AssertIOAllowed();
[email protected]6f5399412013-05-08 22:02:36201 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
202 return true;
203 if (error)
[email protected]5553d5b2013-07-01 23:07:36204 *error = ErrnoToPlatformFileError(errno);
[email protected]6f5399412013-05-08 22:02:36205 return false;
[email protected]c5866dca2009-05-19 17:21:07206}
207
[email protected]9e66a9b2013-05-08 05:46:20208bool CopyDirectory(const FilePath& from_path,
209 const FilePath& to_path,
[email protected]21dec3872008-09-18 19:15:54210 bool recursive) {
[email protected]f0ff2ad2013-07-09 17:42:26211 ThreadRestrictions::AssertIOAllowed();
[email protected]21dec3872008-09-18 19:15:54212 // Some old callers of CopyDirectory want it to support wildcards.
213 // After some discussion, we decided to fix those callers.
214 // Break loudly here if anyone tries to do this.
[email protected]9e66a9b2013-05-08 05:46:20215 // TODO(evanm): remove this once we're sure it's ok.
[email protected]640517f2008-10-30 23:54:04216 DCHECK(to_path.value().find('*') == std::string::npos);
217 DCHECK(from_path.value().find('*') == std::string::npos);
[email protected]21dec3872008-09-18 19:15:54218
219 char top_dir[PATH_MAX];
[email protected]f0ff2ad2013-07-09 17:42:26220 if (strlcpy(top_dir, from_path.value().c_str(),
221 arraysize(top_dir)) >= arraysize(top_dir)) {
[email protected]21dec3872008-09-18 19:15:54222 return false;
223 }
224
[email protected]49930c3a2009-08-06 21:23:07225 // This function does not properly handle destinations within the source
226 FilePath real_to_path = to_path;
[email protected]7567484142013-07-11 17:36:07227 if (PathExists(real_to_path)) {
[email protected]15476932013-04-12 05:17:15228 real_to_path = MakeAbsoluteFilePath(real_to_path);
229 if (real_to_path.empty())
[email protected]49930c3a2009-08-06 21:23:07230 return false;
231 } else {
[email protected]15476932013-04-12 05:17:15232 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
233 if (real_to_path.empty())
[email protected]49930c3a2009-08-06 21:23:07234 return false;
235 }
[email protected]15476932013-04-12 05:17:15236 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
237 if (real_from_path.empty())
[email protected]21dec3872008-09-18 19:15:54238 return false;
[email protected]49930c3a2009-08-06 21:23:07239 if (real_to_path.value().size() >= real_from_path.value().size() &&
240 real_to_path.value().compare(0, real_from_path.value().size(),
241 real_from_path.value()) == 0)
242 return false;
243
244 bool success = true;
[email protected]84c3f162012-08-12 01:57:23245 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
[email protected]49930c3a2009-08-06 21:23:07246 if (recursive)
[email protected]84c3f162012-08-12 01:57:23247 traverse_type |= FileEnumerator::DIRECTORIES;
[email protected]49930c3a2009-08-06 21:23:07248 FileEnumerator traversal(from_path, recursive, traverse_type);
249
[email protected]abbc5732009-10-13 17:57:27250 // We have to mimic windows behavior here. |to_path| may not exist yet,
[email protected]bc6a9012009-10-15 01:11:44251 // start the loop with |to_path|.
[email protected]25a4c1c2013-06-08 04:53:36252 struct stat from_stat;
[email protected]49930c3a2009-08-06 21:23:07253 FilePath current = from_path;
[email protected]25a4c1c2013-06-08 04:53:36254 if (stat(from_path.value().c_str(), &from_stat) < 0) {
[email protected]a42d4632011-10-26 21:48:00255 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
256 << from_path.value() << " errno = " << errno;
[email protected]49930c3a2009-08-06 21:23:07257 success = false;
[email protected]21dec3872008-09-18 19:15:54258 }
[email protected]bc6a9012009-10-15 01:11:44259 struct stat to_path_stat;
260 FilePath from_path_base = from_path;
261 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
262 S_ISDIR(to_path_stat.st_mode)) {
263 // If the destination already exists and is a directory, then the
264 // top level of source needs to be copied.
265 from_path_base = from_path.DirName();
266 }
267
268 // The Windows version of this function assumes that non-recursive calls
269 // will always have a directory for from_path.
[email protected]25a4c1c2013-06-08 04:53:36270 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
[email protected]21dec3872008-09-18 19:15:54271
[email protected]49930c3a2009-08-06 21:23:07272 while (success && !current.empty()) {
[email protected]92e06492013-01-30 11:38:02273 // current is the source path, including from_path, so append
274 // the suffix after from_path to to_path to create the target_path.
275 FilePath target_path(to_path);
276 if (from_path_base != current) {
277 if (!from_path_base.AppendRelativePath(current, &target_path)) {
278 success = false;
279 break;
280 }
[email protected]ca0209612009-01-13 18:57:46281 }
[email protected]21dec3872008-09-18 19:15:54282
[email protected]25a4c1c2013-06-08 04:53:36283 if (S_ISDIR(from_stat.st_mode)) {
284 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
[email protected]49930c3a2009-08-06 21:23:07285 errno != EEXIST) {
[email protected]a42d4632011-10-26 21:48:00286 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
287 << target_path.value() << " errno = " << errno;
[email protected]49930c3a2009-08-06 21:23:07288 success = false;
289 }
[email protected]25a4c1c2013-06-08 04:53:36290 } else if (S_ISREG(from_stat.st_mode)) {
[email protected]49930c3a2009-08-06 21:23:07291 if (!CopyFile(current, target_path)) {
[email protected]a42d4632011-10-26 21:48:00292 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
293 << target_path.value();
[email protected]49930c3a2009-08-06 21:23:07294 success = false;
295 }
296 } else {
[email protected]a42d4632011-10-26 21:48:00297 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
298 << current.value();
[email protected]21dec3872008-09-18 19:15:54299 }
[email protected]21dec3872008-09-18 19:15:54300
[email protected]49930c3a2009-08-06 21:23:07301 current = traversal.Next();
[email protected]25a4c1c2013-06-08 04:53:36302 if (!current.empty())
303 from_stat = traversal.GetInfo().stat();
[email protected]21dec3872008-09-18 19:15:54304 }
305
[email protected]49930c3a2009-08-06 21:23:07306 return success;
[email protected]b2e97292008-09-02 18:20:34307}
308
[email protected]7567484142013-07-11 17:36:07309bool PathExists(const FilePath& path) {
310 ThreadRestrictions::AssertIOAllowed();
311 return access(path.value().c_str(), F_OK) == 0;
312}
313
[email protected]dcd16612013-07-15 20:18:09314bool PathIsWritable(const FilePath& path) {
315 ThreadRestrictions::AssertIOAllowed();
316 return access(path.value().c_str(), W_OK) == 0;
317}
318
319bool DirectoryExists(const FilePath& path) {
320 ThreadRestrictions::AssertIOAllowed();
321 stat_wrapper_t file_info;
322 if (CallStat(path.value().c_str(), &file_info) == 0)
323 return S_ISDIR(file_info.st_mode);
324 return false;
325}
326
[email protected]f0ff2ad2013-07-09 17:42:26327} // namespace base
328
329// -----------------------------------------------------------------------------
330
331namespace file_util {
332
333using base::stat_wrapper_t;
334using base::CallStat;
335using base::CallLstat;
[email protected]dcd16612013-07-15 20:18:09336using base::DirectoryExists;
[email protected]f0ff2ad2013-07-09 17:42:26337using base::FileEnumerator;
338using base::FilePath;
339using base::MakeAbsoluteFilePath;
340using base::RealPath;
341using base::VerifySpecificPathControlledByUser;
342
[email protected]45301492009-04-23 12:38:08343bool ReadFromFD(int fd, char* buffer, size_t bytes) {
344 size_t total_read = 0;
345 while (total_read < bytes) {
[email protected]157c61b2009-05-01 21:37:31346 ssize_t bytes_read =
347 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
348 if (bytes_read <= 0)
[email protected]45301492009-04-23 12:38:08349 break;
[email protected]157c61b2009-05-01 21:37:31350 total_read += bytes_read;
[email protected]45301492009-04-23 12:38:08351 }
352 return total_read == bytes;
353}
354
[email protected]2e733d102010-11-30 00:43:37355bool CreateSymbolicLink(const FilePath& target_path,
356 const FilePath& symlink_path) {
357 DCHECK(!symlink_path.empty());
358 DCHECK(!target_path.empty());
359 return ::symlink(target_path.value().c_str(),
360 symlink_path.value().c_str()) != -1;
361}
362
363bool ReadSymbolicLink(const FilePath& symlink_path,
364 FilePath* target_path) {
365 DCHECK(!symlink_path.empty());
366 DCHECK(target_path);
367 char buf[PATH_MAX];
368 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
369
[email protected]723571a2010-12-03 17:37:54370 if (count <= 0) {
371 target_path->clear();
[email protected]2e733d102010-11-30 00:43:37372 return false;
[email protected]723571a2010-12-03 17:37:54373 }
[email protected]2e733d102010-11-30 00:43:37374
375 *target_path = FilePath(FilePath::StringType(buf, count));
[email protected]2e733d102010-11-30 00:43:37376 return true;
377}
378
[email protected]5085e442012-07-11 01:24:02379bool GetPosixFilePermissions(const FilePath& path, int* mode) {
380 base::ThreadRestrictions::AssertIOAllowed();
381 DCHECK(mode);
382
383 stat_wrapper_t file_info;
384 // Uses stat(), because on symbolic link, lstat() does not return valid
385 // permission bits in st_mode
386 if (CallStat(path.value().c_str(), &file_info) != 0)
387 return false;
388
389 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
390 return true;
391}
392
393bool SetPosixFilePermissions(const FilePath& path,
394 int mode) {
395 base::ThreadRestrictions::AssertIOAllowed();
396 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
397
398 // Calls stat() so that we can preserve the higher bits like S_ISGID.
399 stat_wrapper_t stat_buf;
400 if (CallStat(path.value().c_str(), &stat_buf) != 0)
401 return false;
402
403 // Clears the existing permission bits, and adds the new ones.
404 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
405 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
406
407 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
408 return false;
409
410 return true;
411}
412
[email protected]9e51af92009-02-04 00:58:39413// Creates and opens a temporary file in |directory|, returning the
[email protected]16eac0a72009-09-11 17:33:50414// file descriptor. |path| is set to the temporary file path.
415// This function does NOT unlink() the file.
[email protected]9e51af92009-02-04 00:58:39416int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
[email protected]ba74b0d22010-10-23 05:19:20417 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
[email protected]5553d5b2013-07-01 23:07:36418 *path = directory.Append(base::TempFileName());
[email protected]9e51af92009-02-04 00:58:39419 const std::string& tmpdir_string = path->value();
[email protected]778e8c52008-09-11 17:36:23420 // this should be OK since mkstemp just replaces characters in place
421 char* buffer = const_cast<char*>(tmpdir_string.c_str());
[email protected]392264c2008-11-11 00:01:38422
[email protected]b266ffea2011-04-12 06:07:25423 return HANDLE_EINTR(mkstemp(buffer));
[email protected]9e51af92009-02-04 00:58:39424}
425
[email protected]33edeab2009-08-18 16:07:55426bool CreateTemporaryFile(FilePath* path) {
[email protected]ba74b0d22010-10-23 05:19:20427 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]9e51af92009-02-04 00:58:39428 FilePath directory;
429 if (!GetTempDir(&directory))
430 return false;
431 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
[email protected]b2e97292008-09-02 18:20:34432 if (fd < 0)
433 return false;
[email protected]2e90bee2011-04-12 06:51:22434 ignore_result(HANDLE_EINTR(close(fd)));
[email protected]b2e97292008-09-02 18:20:34435 return true;
436}
437
[email protected]103dccfa2011-12-06 18:07:05438FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
[email protected]9e51af92009-02-04 00:58:39439 FilePath directory;
[email protected]103dccfa2011-12-06 18:07:05440 if (!GetShmemTempDir(&directory, executable))
[email protected]628476aa2010-06-10 22:56:23441 return NULL;
[email protected]9e51af92009-02-04 00:58:39442
[email protected]6faa0e0d2009-04-28 06:50:36443 return CreateAndOpenTemporaryFileInDir(directory, path);
444}
445
446FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
447 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
[email protected]9e51af92009-02-04 00:58:39448 if (fd < 0)
449 return NULL;
450
[email protected]139063bd2011-04-18 19:05:53451 FILE* file = fdopen(fd, "a+");
452 if (!file)
453 ignore_result(HANDLE_EINTR(close(fd)));
454 return file;
[email protected]9e51af92009-02-04 00:58:39455}
[email protected]6445c402009-09-11 20:06:27456
457bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
[email protected]ba74b0d22010-10-23 05:19:20458 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]6445c402009-09-11 20:06:27459 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
[email protected]b266ffea2011-04-12 06:07:25460 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
[email protected]9ccbb372008-10-10 18:50:32461}
462
[email protected]b0b3abd92010-04-30 17:00:09463static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
464 const FilePath::StringType& name_tmpl,
465 FilePath* new_dir) {
[email protected]ba74b0d22010-10-23 05:19:20466 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
[email protected]a42d4632011-10-26 21:48:00467 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
468 << "Directory name template must contain \"XXXXXX\".";
[email protected]b0b3abd92010-04-30 17:00:09469
470 FilePath sub_dir = base_dir.Append(name_tmpl);
471 std::string sub_dir_string = sub_dir.value();
472
473 // this should be OK since mkdtemp just replaces characters in place
474 char* buffer = const_cast<char*>(sub_dir_string.c_str());
475 char* dtemp = mkdtemp(buffer);
[email protected]3ad035d22010-07-28 21:00:51476 if (!dtemp) {
477 DPLOG(ERROR) << "mkdtemp";
[email protected]b0b3abd92010-04-30 17:00:09478 return false;
[email protected]3ad035d22010-07-28 21:00:51479 }
[email protected]b0b3abd92010-04-30 17:00:09480 *new_dir = FilePath(dtemp);
481 return true;
482}
483
484bool CreateTemporaryDirInDir(const FilePath& base_dir,
485 const FilePath::StringType& prefix,
[email protected]046062e82010-06-30 07:19:11486 FilePath* new_dir) {
[email protected]b0b3abd92010-04-30 17:00:09487 FilePath::StringType mkdtemp_template = prefix;
488 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
489 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
490}
491
[email protected]7e1fde6a2008-12-23 20:20:10492bool CreateNewTempDirectory(const FilePath::StringType& prefix,
493 FilePath* new_temp_path) {
[email protected]392264c2008-11-11 00:01:38494 FilePath tmpdir;
[email protected]b2e97292008-09-02 18:20:34495 if (!GetTempDir(&tmpdir))
496 return false;
[email protected]b0b3abd92010-04-30 17:00:09497
[email protected]5553d5b2013-07-01 23:07:36498 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
499 new_temp_path);
[email protected]b2e97292008-09-02 18:20:34500}
501
[email protected]cfd23d22013-06-11 03:50:25502bool CreateDirectoryAndGetError(const FilePath& full_path,
503 base::PlatformFileError* error) {
[email protected]ba74b0d22010-10-23 05:19:20504 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
[email protected]640517f2008-10-30 23:54:04505 std::vector<FilePath> subpaths;
506
507 // Collect a list of all parent directories.
508 FilePath last_path = full_path;
509 subpaths.push_back(full_path);
510 for (FilePath path = full_path.DirName();
511 path.value() != last_path.value(); path = path.DirName()) {
512 subpaths.push_back(path);
513 last_path = path;
514 }
515
516 // Iterate through the parents and create the missing ones.
517 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
518 i != subpaths.rend(); ++i) {
[email protected]0ba86e42010-03-17 21:39:42519 if (DirectoryExists(*i))
520 continue;
521 if (mkdir(i->value().c_str(), 0700) == 0)
522 continue;
523 // Mkdir failed, but it might have failed with EEXIST, or some other error
524 // due to the the directory appearing out of thin air. This can occur if
525 // two processes are trying to create the same file system tree at the same
526 // time. Check to see if it exists and make sure it is a directory.
[email protected]cfd23d22013-06-11 03:50:25527 int saved_errno = errno;
528 if (!DirectoryExists(*i)) {
529 if (error)
530 *error = base::ErrnoToPlatformFileError(saved_errno);
[email protected]0ba86e42010-03-17 21:39:42531 return false;
[email protected]cfd23d22013-06-11 03:50:25532 }
[email protected]b2e97292008-09-02 18:20:34533 }
534 return true;
535}
536
[email protected]992c73e2013-04-04 09:05:21537base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
538 const int kMaxAttempts = 20;
539 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
[email protected]007b3f82013-04-09 08:46:45540 int uniquifier =
541 GetUniquePathNumber(path, base::FilePath::StringType());
[email protected]992c73e2013-04-04 09:05:21542 if (uniquifier < 0)
543 break;
544 base::FilePath test_path = (uniquifier == 0) ? path :
545 path.InsertBeforeExtensionASCII(
546 base::StringPrintf(" (%d)", uniquifier));
547 if (mkdir(test_path.value().c_str(), 0777) == 0)
548 return test_path;
549 else if (errno != EEXIST)
550 break;
551 }
552 return base::FilePath();
553}
554
[email protected]cd78ad52011-05-31 23:10:06555// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
556// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
557bool IsLink(const FilePath& file_path) {
[email protected]7122db22012-06-30 05:26:59558 stat_wrapper_t st;
[email protected]cd78ad52011-05-31 23:10:06559 // If we can't lstat the file, it's safe to assume that the file won't at
560 // least be a 'followable' link.
[email protected]7122db22012-06-30 05:26:59561 if (CallLstat(file_path.value().c_str(), &st) != 0)
[email protected]cd78ad52011-05-31 23:10:06562 return false;
563
564 if (S_ISLNK(st.st_mode))
565 return true;
566 else
567 return false;
568}
569
[email protected]2f0193c22010-09-03 02:28:37570bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
[email protected]fb66f9d2009-09-07 16:39:46571 stat_wrapper_t file_info;
572 if (CallStat(file_path.value().c_str(), &file_info) != 0)
[email protected]b2e97292008-09-02 18:20:34573 return false;
[email protected]f5e3da4d2008-09-26 01:04:08574 results->is_directory = S_ISDIR(file_info.st_mode);
575 results->size = file_info.st_size;
[email protected]92bb9cb2013-06-10 09:41:35576#if defined(OS_MACOSX)
577 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
578 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
579 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
580#elif defined(OS_ANDROID)
[email protected]5ef323892009-07-24 16:13:53581 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
[email protected]2f0193c22010-09-03 02:28:37582 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
583 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
[email protected]92bb9cb2013-06-10 09:41:35584#else
585 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
586 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
587 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
588#endif
[email protected]b2e97292008-09-02 18:20:34589 return true;
590}
591
[email protected]825003f2009-05-14 17:49:23592bool GetInode(const FilePath& path, ino_t* inode) {
[email protected]ba74b0d22010-10-23 05:19:20593 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
[email protected]825003f2009-05-14 17:49:23594 struct stat buffer;
595 int result = stat(path.value().c_str(), &buffer);
596 if (result < 0)
597 return false;
598
599 *inode = buffer.st_ino;
600 return true;
601}
602
[email protected]836f1342008-10-01 17:40:13603FILE* OpenFile(const std::string& filename, const char* mode) {
[email protected]a9cd2a652008-11-17 21:01:19604 return OpenFile(FilePath(filename), mode);
[email protected]836f1342008-10-01 17:40:13605}
606
[email protected]a9cd2a652008-11-17 21:01:19607FILE* OpenFile(const FilePath& filename, const char* mode) {
[email protected]ba74b0d22010-10-23 05:19:20608 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25609 FILE* result = NULL;
610 do {
611 result = fopen(filename.value().c_str(), mode);
612 } while (!result && errno == EINTR);
613 return result;
[email protected]836f1342008-10-01 17:40:13614}
615
[email protected]c870c762009-01-28 05:47:15616int ReadFile(const FilePath& filename, char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20617 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25618 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
[email protected]b2e97292008-09-02 18:20:34619 if (fd < 0)
620 return -1;
[email protected]a9cd2a652008-11-17 21:01:19621
[email protected]cabe39c2010-02-02 02:28:16622 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
623 if (int ret = HANDLE_EINTR(close(fd)) < 0)
624 return ret;
625 return bytes_read;
[email protected]b2e97292008-09-02 18:20:34626}
627
[email protected]c870c762009-01-28 05:47:15628int WriteFile(const FilePath& filename, const char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20629 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25630 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
[email protected]b2e97292008-09-02 18:20:34631 if (fd < 0)
632 return -1;
[email protected]778e8c52008-09-11 17:36:23633
[email protected]cabe39c2010-02-02 02:28:16634 int bytes_written = WriteFileDescriptor(fd, data, size);
635 if (int ret = HANDLE_EINTR(close(fd)) < 0)
636 return ret;
637 return bytes_written;
[email protected]fbea0232009-09-16 00:29:22638}
639
640int WriteFileDescriptor(const int fd, const char* data, int size) {
641 // Allow for partial writes.
642 ssize_t bytes_written_total = 0;
643 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
644 bytes_written_total += bytes_written_partial) {
645 bytes_written_partial =
646 HANDLE_EINTR(write(fd, data + bytes_written_total,
647 size - bytes_written_total));
648 if (bytes_written_partial < 0)
649 return -1;
650 }
651
[email protected]778e8c52008-09-11 17:36:23652 return bytes_written_total;
[email protected]b2e97292008-09-02 18:20:34653}
654
[email protected]891128f2012-04-29 12:57:10655int AppendToFile(const FilePath& filename, const char* data, int size) {
656 base::ThreadRestrictions::AssertIOAllowed();
657 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
658 if (fd < 0)
659 return -1;
660
661 int bytes_written = WriteFileDescriptor(fd, data, size);
662 if (int ret = HANDLE_EINTR(close(fd)) < 0)
663 return ret;
664 return bytes_written;
665}
666
[email protected]b2e97292008-09-02 18:20:34667// Gets the current working directory for the process.
[email protected]640517f2008-10-30 23:54:04668bool GetCurrentDirectory(FilePath* dir) {
[email protected]ba74b0d22010-10-23 05:19:20669 // getcwd can return ENOENT, which implies it checks against the disk.
670 base::ThreadRestrictions::AssertIOAllowed();
671
[email protected]b2e97292008-09-02 18:20:34672 char system_buffer[PATH_MAX] = "";
[email protected]640517f2008-10-30 23:54:04673 if (!getcwd(system_buffer, sizeof(system_buffer))) {
674 NOTREACHED();
675 return false;
676 }
677 *dir = FilePath(system_buffer);
[email protected]b2e97292008-09-02 18:20:34678 return true;
679}
680
681// Sets the current working directory for the process.
[email protected]a9cd2a652008-11-17 21:01:19682bool SetCurrentDirectory(const FilePath& path) {
[email protected]ba74b0d22010-10-23 05:19:20683 base::ThreadRestrictions::AssertIOAllowed();
[email protected]a9cd2a652008-11-17 21:01:19684 int ret = chdir(path.value().c_str());
685 return !ret;
[email protected]b2e97292008-09-02 18:20:34686}
[email protected]a9cd2a652008-11-17 21:01:19687
[email protected]6f5f4322010-06-09 22:56:48688bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
689 FilePath real_path_result;
690 if (!RealPath(path, &real_path_result))
[email protected]01e2a1f2010-05-12 15:13:57691 return false;
692
[email protected]6f5f4322010-06-09 22:56:48693 // To be consistant with windows, fail if |real_path_result| is a
694 // directory.
695 stat_wrapper_t file_info;
696 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
697 S_ISDIR(file_info.st_mode))
698 return false;
699
700 *normalized_path = real_path_result;
[email protected]01e2a1f2010-05-12 15:13:57701 return true;
702}
703
[email protected]84cb1912010-04-21 21:11:36704#if !defined(OS_MACOSX)
705bool GetTempDir(FilePath* path) {
706 const char* tmp = getenv("TMPDIR");
707 if (tmp)
708 *path = FilePath(tmp);
709 else
[email protected]f7d69972011-06-21 22:34:50710#if defined(OS_ANDROID)
[email protected]0eae7eb2012-05-17 20:09:06711 return PathService::Get(base::DIR_CACHE, path);
[email protected]f7d69972011-06-21 22:34:50712#else
[email protected]84cb1912010-04-21 21:11:36713 *path = FilePath("/tmp");
[email protected]f7d69972011-06-21 22:34:50714#endif
[email protected]84cb1912010-04-21 21:11:36715 return true;
716}
717
[email protected]f7d69972011-06-21 22:34:50718#if !defined(OS_ANDROID)
[email protected]103dccfa2011-12-06 18:07:05719
[email protected]167ec822011-10-24 22:05:27720#if defined(OS_LINUX)
[email protected]103dccfa2011-12-06 18:07:05721// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
722// This depends on the mount options used for /dev/shm, which vary among
723// different Linux distributions and possibly local configuration. It also
724// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
725// but its kernel allows mprotect with PROT_EXEC anyway.
726
727namespace {
728
729bool DetermineDevShmExecutable() {
730 bool result = false;
731 FilePath path;
732 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
733 if (fd >= 0) {
734 ScopedFD shm_fd_closer(&fd);
[email protected]dd3aa792013-07-16 19:10:23735 DeleteFile(path, false);
[email protected]37e77e02011-12-22 22:31:44736 long sysconf_result = sysconf(_SC_PAGESIZE);
737 CHECK_GE(sysconf_result, 0);
738 size_t pagesize = static_cast<size_t>(sysconf_result);
739 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
[email protected]103dccfa2011-12-06 18:07:05740 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
741 if (mapping != MAP_FAILED) {
742 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
743 result = true;
744 munmap(mapping, pagesize);
745 }
746 }
747 return result;
[email protected]84cb1912010-04-21 21:11:36748}
[email protected]103dccfa2011-12-06 18:07:05749
750}; // namespace
751#endif // defined(OS_LINUX)
752
753bool GetShmemTempDir(FilePath* path, bool executable) {
754#if defined(OS_LINUX)
755 bool use_dev_shm = true;
756 if (executable) {
757 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
758 use_dev_shm = s_dev_shm_executable;
759 }
760 if (use_dev_shm) {
761 *path = FilePath("/dev/shm");
762 return true;
763 }
[email protected]f7d69972011-06-21 22:34:50764#endif
[email protected]103dccfa2011-12-06 18:07:05765 return GetTempDir(path);
766}
767#endif // !defined(OS_ANDROID)
[email protected]84cb1912010-04-21 21:11:36768
[email protected]1c657852010-04-22 23:28:05769FilePath GetHomeDir() {
[email protected]774727282012-08-06 09:14:44770#if defined(OS_CHROMEOS)
[email protected]49c4cf852013-09-27 19:28:24771 if (base::SysInfo::IsRunningOnChromeOS())
[email protected]774727282012-08-06 09:14:44772 return FilePath("/home/chronos/user");
773#endif
774
[email protected]1c657852010-04-22 23:28:05775 const char* home_dir = getenv("HOME");
776 if (home_dir && home_dir[0])
777 return FilePath(home_dir);
778
[email protected]f7d69972011-06-21 22:34:50779#if defined(OS_ANDROID)
[email protected]a42d4632011-10-26 21:48:00780 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
[email protected]4ab65012013-11-07 11:38:32781#elif !defined(OS_CHROMEOS)
[email protected]ba74b0d22010-10-23 05:19:20782 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
783 base::ThreadRestrictions::AssertIOAllowed();
784
[email protected]1c657852010-04-22 23:28:05785 home_dir = g_get_home_dir();
786 if (home_dir && home_dir[0])
787 return FilePath(home_dir);
[email protected]f7d69972011-06-21 22:34:50788#endif
[email protected]1c657852010-04-22 23:28:05789
790 FilePath rv;
791 if (file_util::GetTempDir(&rv))
792 return rv;
793
794 // Last resort.
795 return FilePath("/tmp");
796}
[email protected]92e44ae0a2012-07-23 08:22:44797#endif // !defined(OS_MACOSX)
[email protected]84cb1912010-04-21 21:11:36798
[email protected]73e4c362011-09-22 14:47:18799bool VerifyPathControlledByUser(const FilePath& base,
800 const FilePath& path,
801 uid_t owner_uid,
[email protected]7312f42a2011-10-17 21:30:29802 const std::set<gid_t>& group_gids) {
[email protected]73e4c362011-09-22 14:47:18803 if (base != path && !base.IsParent(path)) {
[email protected]a42d4632011-10-26 21:48:00804 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
805 << base.value() << "\", path = \"" << path.value() << "\"";
[email protected]73e4c362011-09-22 14:47:18806 return false;
807 }
808
809 std::vector<FilePath::StringType> base_components;
810 std::vector<FilePath::StringType> path_components;
811
812 base.GetComponents(&base_components);
813 path.GetComponents(&path_components);
814
815 std::vector<FilePath::StringType>::const_iterator ib, ip;
816 for (ib = base_components.begin(), ip = path_components.begin();
817 ib != base_components.end(); ++ib, ++ip) {
818 // |base| must be a subpath of |path|, so all components should match.
819 // If these CHECKs fail, look at the test that base is a parent of
820 // path at the top of this function.
[email protected]a42d4632011-10-26 21:48:00821 DCHECK(ip != path_components.end());
822 DCHECK(*ip == *ib);
[email protected]73e4c362011-09-22 14:47:18823 }
824
825 FilePath current_path = base;
[email protected]7312f42a2011-10-17 21:30:29826 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
[email protected]73e4c362011-09-22 14:47:18827 return false;
828
829 for (; ip != path_components.end(); ++ip) {
830 current_path = current_path.Append(*ip);
[email protected]7312f42a2011-10-17 21:30:29831 if (!VerifySpecificPathControlledByUser(
832 current_path, owner_uid, group_gids))
[email protected]73e4c362011-09-22 14:47:18833 return false;
834 }
835 return true;
836}
837
[email protected]4bd46792012-07-09 14:40:39838#if defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]73e4c362011-09-22 14:47:18839bool VerifyPathControlledByAdmin(const FilePath& path) {
840 const unsigned kRootUid = 0;
841 const FilePath kFileSystemRoot("/");
842
843 // The name of the administrator group on mac os.
[email protected]7312f42a2011-10-17 21:30:29844 const char* const kAdminGroupNames[] = {
845 "admin",
846 "wheel"
847 };
[email protected]73e4c362011-09-22 14:47:18848
849 // Reading the groups database may touch the file system.
850 base::ThreadRestrictions::AssertIOAllowed();
851
[email protected]7312f42a2011-10-17 21:30:29852 std::set<gid_t> allowed_group_ids;
853 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
854 struct group *group_record = getgrnam(kAdminGroupNames[i]);
855 if (!group_record) {
[email protected]a42d4632011-10-26 21:48:00856 DPLOG(ERROR) << "Could not get the group ID of group \""
857 << kAdminGroupNames[i] << "\".";
[email protected]7312f42a2011-10-17 21:30:29858 continue;
859 }
860
861 allowed_group_ids.insert(group_record->gr_gid);
[email protected]73e4c362011-09-22 14:47:18862 }
863
864 return VerifyPathControlledByUser(
[email protected]7312f42a2011-10-17 21:30:29865 kFileSystemRoot, path, kRootUid, allowed_group_ids);
[email protected]73e4c362011-09-22 14:47:18866}
[email protected]eba29932012-07-24 11:23:32867#endif // defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]73e4c362011-09-22 14:47:18868
[email protected]59480302013-02-21 03:24:08869int GetMaximumPathComponentLength(const FilePath& path) {
870 base::ThreadRestrictions::AssertIOAllowed();
871 return pathconf(path.value().c_str(), _PC_NAME_MAX);
872}
873
[email protected]33e585a2010-11-20 03:38:15874} // namespace file_util
[email protected]f0ff2ad2013-07-09 17:42:26875
876namespace base {
877namespace internal {
878
879bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
880 ThreadRestrictions::AssertIOAllowed();
881 // Windows compatibility: if to_path exists, from_path and to_path
882 // must be the same type, either both files, or both directories.
883 stat_wrapper_t to_file_info;
884 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
885 stat_wrapper_t from_file_info;
886 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
887 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
888 return false;
889 } else {
890 return false;
891 }
892 }
893
894 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
895 return true;
896
897 if (!CopyDirectory(from_path, to_path, true))
898 return false;
899
[email protected]dd3aa792013-07-16 19:10:23900 DeleteFile(from_path, true);
[email protected]f0ff2ad2013-07-09 17:42:26901 return true;
902}
903
904#if !defined(OS_MACOSX)
905// Mac has its own implementation, this is for all other Posix systems.
906bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
907 ThreadRestrictions::AssertIOAllowed();
908 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
909 if (infile < 0)
910 return false;
911
912 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
913 if (outfile < 0) {
914 ignore_result(HANDLE_EINTR(close(infile)));
915 return false;
916 }
917
918 const size_t kBufferSize = 32768;
919 std::vector<char> buffer(kBufferSize);
920 bool result = true;
921
922 while (result) {
923 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
924 if (bytes_read < 0) {
925 result = false;
926 break;
927 }
928 if (bytes_read == 0)
929 break;
930 // Allow for partial writes
931 ssize_t bytes_written_per_read = 0;
932 do {
933 ssize_t bytes_written_partial = HANDLE_EINTR(write(
934 outfile,
935 &buffer[bytes_written_per_read],
936 bytes_read - bytes_written_per_read));
937 if (bytes_written_partial < 0) {
938 result = false;
939 break;
940 }
941 bytes_written_per_read += bytes_written_partial;
942 } while (bytes_written_per_read < bytes_read);
943 }
944
945 if (HANDLE_EINTR(close(infile)) < 0)
946 result = false;
947 if (HANDLE_EINTR(close(outfile)) < 0)
948 result = false;
949
950 return result;
951}
952#endif // !defined(OS_MACOSX)
953
954} // namespace internal
955} // namespace base