blob: 323f5aa561359c74c2ba34934cc20755dec5bcd4 [file] [log] [blame]
[email protected]3b63f8f42011-03-28 01:54:151// Copyright (c) 2011 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>
10#include <fnmatch.h>
[email protected]73e4c362011-09-22 14:47:1811#include <grp.h>
[email protected]b2e97292008-09-02 18:20:3412#include <libgen.h>
[email protected]e92dffe2010-05-12 21:36:3913#include <limits.h>
[email protected]836f1342008-10-01 17:40:1314#include <stdio.h>
[email protected]1c657852010-04-22 23:28:0515#include <stdlib.h>
[email protected]21dec3872008-09-18 19:15:5416#include <string.h>
[email protected]b2e97292008-09-02 18:20:3417#include <sys/errno.h>
[email protected]7856bb82008-12-12 23:43:0318#include <sys/mman.h>
[email protected]01e2a1f2010-05-12 15:13:5719#include <sys/param.h>
[email protected]b2e97292008-09-02 18:20:3420#include <sys/stat.h>
[email protected]ec3d1452010-02-18 10:02:2621#include <sys/time.h>
[email protected]4b7743de2009-04-21 01:50:3922#include <sys/types.h>
[email protected]b2e97292008-09-02 18:20:3423#include <time.h>
[email protected]4b7743de2009-04-21 01:50:3924#include <unistd.h>
[email protected]b2e97292008-09-02 18:20:3425
[email protected]3224dcd2009-09-16 17:31:2526#if defined(OS_MACOSX)
27#include <AvailabilityMacros.h>
[email protected]151c4a62011-04-22 04:15:1328#include "base/mac/foundation_util.h"
[email protected]f7d69972011-06-21 22:34:5029#elif !defined(OS_ANDROID)
[email protected]1c657852010-04-22 23:28:0530#include <glib.h>
[email protected]3224dcd2009-09-16 17:31:2531#endif
32
[email protected]b2e97292008-09-02 18:20:3433#include <fstream>
34
35#include "base/basictypes.h"
[email protected]157c61b2009-05-01 21:37:3136#include "base/eintr_wrapper.h"
[email protected]640517f2008-10-30 23:54:0437#include "base/file_path.h"
[email protected]b2e97292008-09-02 18:20:3438#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1539#include "base/memory/scoped_ptr.h"
40#include "base/memory/singleton.h"
[email protected]b2e97292008-09-02 18:20:3441#include "base/string_util.h"
[email protected]151c4a62011-04-22 04:15:1342#include "base/stringprintf.h"
[email protected]807bc042009-07-15 01:32:0243#include "base/sys_string_conversions.h"
[email protected]34b99632011-01-01 01:01:0644#include "base/threading/thread_restrictions.h"
[email protected]4b7743de2009-04-21 01:50:3945#include "base/time.h"
[email protected]047a03f2009-10-07 02:10:2046#include "base/utf_string_conversions.h"
[email protected]172c5502009-06-24 03:29:2647
[email protected]f7d69972011-06-21 22:34:5048#if defined(OS_ANDROID)
49#include "base/os_compat_android.h"
50#endif
51
[email protected]b2e97292008-09-02 18:20:3452namespace file_util {
53
[email protected]6f5f4322010-06-09 22:56:4854namespace {
55
[email protected]73e4c362011-09-22 14:47:1856#if defined(OS_OPENBSD) || defined(OS_FREEBSD) || \
57 (defined(OS_MACOSX) && \
58 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
59typedef struct stat stat_wrapper_t;
60static int CallStat(const char *path, stat_wrapper_t *sb) {
61 base::ThreadRestrictions::AssertIOAllowed();
62 return stat(path, sb);
63}
64static int CallLstat(const char *path, stat_wrapper_t *sb) {
65 base::ThreadRestrictions::AssertIOAllowed();
66 return lstat(path, sb);
67}
68#else
69typedef struct stat64 stat_wrapper_t;
70static int CallStat(const char *path, stat_wrapper_t *sb) {
71 base::ThreadRestrictions::AssertIOAllowed();
72 return stat64(path, sb);
73}
74static int CallLstat(const char *path, stat_wrapper_t *sb) {
75 base::ThreadRestrictions::AssertIOAllowed();
76 return lstat64(path, sb);
77}
78#endif
79
[email protected]6f5f4322010-06-09 22:56:4880// Helper for NormalizeFilePath(), defined below.
81bool RealPath(const FilePath& path, FilePath* real_path) {
[email protected]ba74b0d22010-10-23 05:19:2082 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
[email protected]6f5f4322010-06-09 22:56:4883 FilePath::CharType buf[PATH_MAX];
84 if (!realpath(path.value().c_str(), buf))
85 return false;
86
87 *real_path = FilePath(buf);
88 return true;
89}
90
[email protected]73e4c362011-09-22 14:47:1891// Helper for VerifyPathControlledByUser.
92bool VerifySpecificPathControlledByUser(const FilePath& path,
93 uid_t owner_uid,
94 gid_t group_gid) {
95 stat_wrapper_t stat_info;
96 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
97 PLOG(ERROR) << "Failed to get information on path "
98 << path.value();
99 return false;
100 }
[email protected]6f5f4322010-06-09 22:56:48101
[email protected]73e4c362011-09-22 14:47:18102 if (S_ISLNK(stat_info.st_mode)) {
103 LOG(ERROR) << "Path " << path.value()
104 << " is a symbolic link.";
105 return false;
106 }
107
108 if (stat_info.st_uid != owner_uid) {
109 LOG(ERROR) << "Path " << path.value()
110 << " is owned by the wrong user.";
111 return false;
112 }
113
114 if (stat_info.st_gid != group_gid) {
115 LOG(ERROR) << "Path " << path.value()
116 << " is owned by the wrong group.";
117 return false;
118 }
119
120 if (stat_info.st_mode & S_IWOTH) {
121 LOG(ERROR) << "Path " << path.value()
122 << " is writable by any user.";
123 return false;
124 }
125
126 return true;
[email protected]fb66f9d2009-09-07 16:39:46127}
[email protected]73e4c362011-09-22 14:47:18128
129} // namespace
[email protected]fb66f9d2009-09-07 16:39:46130
[email protected]151c4a62011-04-22 04:15:13131static std::string TempFileName() {
132#if defined(OS_MACOSX)
133 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
134#endif
[email protected]fb66f9d2009-09-07 16:39:46135
[email protected]22a087f2009-03-17 19:17:43136#if defined(GOOGLE_CHROME_BUILD)
[email protected]151c4a62011-04-22 04:15:13137 return std::string(".com.google.Chrome.XXXXXX");
[email protected]22a087f2009-03-17 19:17:43138#else
[email protected]151c4a62011-04-22 04:15:13139 return std::string(".org.chromium.Chromium.XXXXXX");
[email protected]22a087f2009-03-17 19:17:43140#endif
[email protected]151c4a62011-04-22 04:15:13141}
[email protected]778e8c52008-09-11 17:36:23142
[email protected]640517f2008-10-30 23:54:04143bool AbsolutePath(FilePath* path) {
[email protected]ba74b0d22010-10-23 05:19:20144 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
[email protected]b2e97292008-09-02 18:20:34145 char full_path[PATH_MAX];
[email protected]640517f2008-10-30 23:54:04146 if (realpath(path->value().c_str(), full_path) == NULL)
[email protected]b2e97292008-09-02 18:20:34147 return false;
[email protected]640517f2008-10-30 23:54:04148 *path = FilePath(full_path);
[email protected]b2e97292008-09-02 18:20:34149 return true;
150}
151
[email protected]4b7743de2009-04-21 01:50:39152int CountFilesCreatedAfter(const FilePath& path,
153 const base::Time& comparison_time) {
[email protected]ba74b0d22010-10-23 05:19:20154 base::ThreadRestrictions::AssertIOAllowed();
[email protected]4b7743de2009-04-21 01:50:39155 int file_count = 0;
156
157 DIR* dir = opendir(path.value().c_str());
158 if (dir) {
[email protected]8d578822010-01-25 23:54:54159#if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_FREEBSD) && \
[email protected]f7d69972011-06-21 22:34:50160 !defined(OS_OPENBSD) && !defined(OS_SOLARIS) && !defined(OS_ANDROID)
[email protected]e43eddf12009-12-29 00:32:52161 #error Port warning: depending on the definition of struct dirent, \
162 additional space for pathname may be needed
[email protected]49930c3a2009-08-06 21:23:07163#endif
[email protected]2126577b2009-04-23 15:05:19164 struct dirent ent_buf;
[email protected]4b7743de2009-04-21 01:50:39165 struct dirent* ent;
[email protected]2126577b2009-04-23 15:05:19166 while (readdir_r(dir, &ent_buf, &ent) == 0 && ent) {
[email protected]4b7743de2009-04-21 01:50:39167 if ((strcmp(ent->d_name, ".") == 0) ||
168 (strcmp(ent->d_name, "..") == 0))
169 continue;
170
[email protected]fb66f9d2009-09-07 16:39:46171 stat_wrapper_t st;
172 int test = CallStat(path.Append(ent->d_name).value().c_str(), &st);
[email protected]4b7743de2009-04-21 01:50:39173 if (test != 0) {
[email protected]57b765672009-10-13 18:27:40174 PLOG(ERROR) << "stat64 failed";
[email protected]4b7743de2009-04-21 01:50:39175 continue;
176 }
[email protected]2126577b2009-04-23 15:05:19177 // Here, we use Time::TimeT(), which discards microseconds. This
178 // means that files which are newer than |comparison_time| may
179 // be considered older. If we don't discard microseconds, it
180 // introduces another issue. Suppose the following case:
181 //
182 // 1. Get |comparison_time| by Time::Now() and the value is 10.1 (secs).
183 // 2. Create a file and the current time is 10.3 (secs).
184 //
185 // As POSIX doesn't have microsecond precision for |st_ctime|,
186 // the creation time of the file created in the step 2 is 10 and
187 // the file is considered older than |comparison_time|. After
188 // all, we may have to accept either of the two issues: 1. files
189 // which are older than |comparison_time| are considered newer
190 // (current implementation) 2. files newer than
191 // |comparison_time| are considered older.
[email protected]e9ad4352010-11-17 11:19:15192 if (static_cast<time_t>(st.st_ctime) >= comparison_time.ToTimeT())
[email protected]4b7743de2009-04-21 01:50:39193 ++file_count;
194 }
195 closedir(dir);
196 }
197 return file_count;
198}
199
[email protected]b2e97292008-09-02 18:20:34200// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
201// which works both with and without the recursive flag. I'm not sure we need
202// that functionality. If not, remove from file_util_win.cc, otherwise add it
203// here.
[email protected]640517f2008-10-30 23:54:04204bool Delete(const FilePath& path, bool recursive) {
[email protected]ba74b0d22010-10-23 05:19:20205 base::ThreadRestrictions::AssertIOAllowed();
[email protected]640517f2008-10-30 23:54:04206 const char* path_str = path.value().c_str();
[email protected]fb66f9d2009-09-07 16:39:46207 stat_wrapper_t file_info;
208 int test = CallStat(path_str, &file_info);
[email protected]b2e97292008-09-02 18:20:34209 if (test != 0) {
210 // The Windows version defines this condition as success.
[email protected]9e51af92009-02-04 00:58:39211 bool ret = (errno == ENOENT || errno == ENOTDIR);
[email protected]b2e97292008-09-02 18:20:34212 return ret;
213 }
214 if (!S_ISDIR(file_info.st_mode))
[email protected]640517f2008-10-30 23:54:04215 return (unlink(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34216 if (!recursive)
[email protected]640517f2008-10-30 23:54:04217 return (rmdir(path_str) == 0);
[email protected]b2e97292008-09-02 18:20:34218
219 bool success = true;
[email protected]49930c3a2009-08-06 21:23:07220 std::stack<std::string> directories;
221 directories.push(path.value());
[email protected]58b7c5a62011-08-15 13:09:27222 FileEnumerator traversal(path, true, static_cast<FileEnumerator::FileType>(
[email protected]49930c3a2009-08-06 21:23:07223 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
224 FileEnumerator::SHOW_SYM_LINKS));
225 for (FilePath current = traversal.Next(); success && !current.empty();
226 current = traversal.Next()) {
227 FileEnumerator::FindInfo info;
228 traversal.GetFindInfo(&info);
229
230 if (S_ISDIR(info.stat.st_mode))
231 directories.push(current.value());
232 else
233 success = (unlink(current.value().c_str()) == 0);
[email protected]21dec3872008-09-18 19:15:54234 }
[email protected]49930c3a2009-08-06 21:23:07235
236 while (success && !directories.empty()) {
237 FilePath dir = FilePath(directories.top());
238 directories.pop();
239 success = (rmdir(dir.value().c_str()) == 0);
[email protected]b2e97292008-09-02 18:20:34240 }
241 return success;
242}
243
[email protected]640517f2008-10-30 23:54:04244bool Move(const FilePath& from_path, const FilePath& to_path) {
[email protected]ba74b0d22010-10-23 05:19:20245 base::ThreadRestrictions::AssertIOAllowed();
[email protected]bc6a9012009-10-15 01:11:44246 // Windows compatibility: if to_path exists, from_path and to_path
247 // must be the same type, either both files, or both directories.
248 stat_wrapper_t to_file_info;
249 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
250 stat_wrapper_t from_file_info;
251 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
252 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
253 return false;
254 } else {
255 return false;
256 }
257 }
258
[email protected]cc7948a2009-03-13 20:01:43259 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
260 return true;
261
262 if (!CopyDirectory(from_path, to_path, true))
263 return false;
264
265 Delete(from_path, true);
266 return true;
[email protected]b2e97292008-09-02 18:20:34267}
268
[email protected]c5866dca2009-05-19 17:21:07269bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
[email protected]ba74b0d22010-10-23 05:19:20270 base::ThreadRestrictions::AssertIOAllowed();
[email protected]c5866dca2009-05-19 17:21:07271 return (rename(from_path.value().c_str(), to_path.value().c_str()) == 0);
272}
273
[email protected]640517f2008-10-30 23:54:04274bool CopyDirectory(const FilePath& from_path,
275 const FilePath& to_path,
[email protected]21dec3872008-09-18 19:15:54276 bool recursive) {
[email protected]ba74b0d22010-10-23 05:19:20277 base::ThreadRestrictions::AssertIOAllowed();
[email protected]21dec3872008-09-18 19:15:54278 // Some old callers of CopyDirectory want it to support wildcards.
279 // After some discussion, we decided to fix those callers.
280 // Break loudly here if anyone tries to do this.
281 // TODO(evanm): remove this once we're sure it's ok.
[email protected]640517f2008-10-30 23:54:04282 DCHECK(to_path.value().find('*') == std::string::npos);
283 DCHECK(from_path.value().find('*') == std::string::npos);
[email protected]21dec3872008-09-18 19:15:54284
285 char top_dir[PATH_MAX];
[email protected]640517f2008-10-30 23:54:04286 if (base::strlcpy(top_dir, from_path.value().c_str(),
[email protected]21dec3872008-09-18 19:15:54287 arraysize(top_dir)) >= arraysize(top_dir)) {
288 return false;
289 }
290
[email protected]49930c3a2009-08-06 21:23:07291 // This function does not properly handle destinations within the source
292 FilePath real_to_path = to_path;
293 if (PathExists(real_to_path)) {
294 if (!AbsolutePath(&real_to_path))
295 return false;
296 } else {
297 real_to_path = real_to_path.DirName();
298 if (!AbsolutePath(&real_to_path))
299 return false;
300 }
301 FilePath real_from_path = from_path;
302 if (!AbsolutePath(&real_from_path))
[email protected]21dec3872008-09-18 19:15:54303 return false;
[email protected]49930c3a2009-08-06 21:23:07304 if (real_to_path.value().size() >= real_from_path.value().size() &&
305 real_to_path.value().compare(0, real_from_path.value().size(),
306 real_from_path.value()) == 0)
307 return false;
308
309 bool success = true;
[email protected]58b7c5a62011-08-15 13:09:27310 FileEnumerator::FileType traverse_type =
311 static_cast<FileEnumerator::FileType>(FileEnumerator::FILES |
[email protected]49930c3a2009-08-06 21:23:07312 FileEnumerator::SHOW_SYM_LINKS);
313 if (recursive)
[email protected]58b7c5a62011-08-15 13:09:27314 traverse_type = static_cast<FileEnumerator::FileType>(
[email protected]49930c3a2009-08-06 21:23:07315 traverse_type | FileEnumerator::DIRECTORIES);
316 FileEnumerator traversal(from_path, recursive, traverse_type);
317
[email protected]abbc5732009-10-13 17:57:27318 // We have to mimic windows behavior here. |to_path| may not exist yet,
[email protected]bc6a9012009-10-15 01:11:44319 // start the loop with |to_path|.
[email protected]49930c3a2009-08-06 21:23:07320 FileEnumerator::FindInfo info;
321 FilePath current = from_path;
322 if (stat(from_path.value().c_str(), &info.stat) < 0) {
323 LOG(ERROR) << "CopyDirectory() couldn't stat source directory: " <<
324 from_path.value() << " errno = " << errno;
325 success = false;
[email protected]21dec3872008-09-18 19:15:54326 }
[email protected]bc6a9012009-10-15 01:11:44327 struct stat to_path_stat;
328 FilePath from_path_base = from_path;
329 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
330 S_ISDIR(to_path_stat.st_mode)) {
331 // If the destination already exists and is a directory, then the
332 // top level of source needs to be copied.
333 from_path_base = from_path.DirName();
334 }
335
336 // The Windows version of this function assumes that non-recursive calls
337 // will always have a directory for from_path.
338 DCHECK(recursive || S_ISDIR(info.stat.st_mode));
[email protected]21dec3872008-09-18 19:15:54339
[email protected]49930c3a2009-08-06 21:23:07340 while (success && !current.empty()) {
341 // current is the source path, including from_path, so paste
[email protected]21dec3872008-09-18 19:15:54342 // the suffix after from_path onto to_path to create the target_path.
[email protected]abbc5732009-10-13 17:57:27343 std::string suffix(&current.value().c_str()[from_path_base.value().size()]);
[email protected]ca0209612009-01-13 18:57:46344 // Strip the leading '/' (if any).
345 if (!suffix.empty()) {
[email protected]6ae340f2009-03-06 09:56:28346 DCHECK_EQ('/', suffix[0]);
[email protected]ca0209612009-01-13 18:57:46347 suffix.erase(0, 1);
348 }
349 const FilePath target_path = to_path.Append(suffix);
[email protected]21dec3872008-09-18 19:15:54350
[email protected]49930c3a2009-08-06 21:23:07351 if (S_ISDIR(info.stat.st_mode)) {
352 if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
353 errno != EEXIST) {
354 LOG(ERROR) << "CopyDirectory() couldn't create directory: " <<
355 target_path.value() << " errno = " << errno;
356 success = false;
357 }
358 } else if (S_ISREG(info.stat.st_mode)) {
359 if (!CopyFile(current, target_path)) {
360 LOG(ERROR) << "CopyDirectory() couldn't create file: " <<
361 target_path.value();
362 success = false;
363 }
364 } else {
365 LOG(WARNING) << "CopyDirectory() skipping non-regular file: " <<
366 current.value();
[email protected]21dec3872008-09-18 19:15:54367 }
[email protected]21dec3872008-09-18 19:15:54368
[email protected]49930c3a2009-08-06 21:23:07369 current = traversal.Next();
370 traversal.GetFindInfo(&info);
[email protected]21dec3872008-09-18 19:15:54371 }
372
[email protected]49930c3a2009-08-06 21:23:07373 return success;
[email protected]b2e97292008-09-02 18:20:34374}
375
[email protected]640517f2008-10-30 23:54:04376bool PathExists(const FilePath& path) {
[email protected]ba74b0d22010-10-23 05:19:20377 base::ThreadRestrictions::AssertIOAllowed();
[email protected]ef944e052010-05-17 15:01:22378 return access(path.value().c_str(), F_OK) == 0;
[email protected]b2e97292008-09-02 18:20:34379}
380
[email protected]7e1fde6a2008-12-23 20:20:10381bool PathIsWritable(const FilePath& path) {
[email protected]ba74b0d22010-10-23 05:19:20382 base::ThreadRestrictions::AssertIOAllowed();
[email protected]ef944e052010-05-17 15:01:22383 return access(path.value().c_str(), W_OK) == 0;
[email protected]7e1fde6a2008-12-23 20:20:10384}
385
[email protected]640517f2008-10-30 23:54:04386bool DirectoryExists(const FilePath& path) {
[email protected]ba74b0d22010-10-23 05:19:20387 base::ThreadRestrictions::AssertIOAllowed();
[email protected]fb66f9d2009-09-07 16:39:46388 stat_wrapper_t file_info;
389 if (CallStat(path.value().c_str(), &file_info) == 0)
[email protected]806b9c62008-09-11 16:09:11390 return S_ISDIR(file_info.st_mode);
391 return false;
392}
393
[email protected]b2e97292008-09-02 18:20:34394// TODO(erikkay): implement
395#if 0
396bool GetFileCreationLocalTimeFromHandle(int fd,
397 LPSYSTEMTIME creation_time) {
398 if (!file_handle)
399 return false;
[email protected]9e51af92009-02-04 00:58:39400
[email protected]b2e97292008-09-02 18:20:34401 FILETIME utc_filetime;
402 if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
403 return false;
[email protected]9e51af92009-02-04 00:58:39404
[email protected]b2e97292008-09-02 18:20:34405 FILETIME local_filetime;
406 if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
407 return false;
[email protected]9e51af92009-02-04 00:58:39408
[email protected]b2e97292008-09-02 18:20:34409 return !!FileTimeToSystemTime(&local_filetime, creation_time);
410}
411
412bool GetFileCreationLocalTime(const std::string& filename,
413 LPSYSTEMTIME creation_time) {
414 ScopedHandle file_handle(
[email protected]9e51af92009-02-04 00:58:39415 CreateFile(filename.c_str(), GENERIC_READ,
[email protected]b2e97292008-09-02 18:20:34416 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
417 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
418 return GetFileCreationLocalTimeFromHandle(file_handle.Get(), creation_time);
419}
420#endif
421
[email protected]45301492009-04-23 12:38:08422bool ReadFromFD(int fd, char* buffer, size_t bytes) {
423 size_t total_read = 0;
424 while (total_read < bytes) {
[email protected]157c61b2009-05-01 21:37:31425 ssize_t bytes_read =
426 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
427 if (bytes_read <= 0)
[email protected]45301492009-04-23 12:38:08428 break;
[email protected]157c61b2009-05-01 21:37:31429 total_read += bytes_read;
[email protected]45301492009-04-23 12:38:08430 }
431 return total_read == bytes;
432}
433
[email protected]2e733d102010-11-30 00:43:37434bool CreateSymbolicLink(const FilePath& target_path,
435 const FilePath& symlink_path) {
436 DCHECK(!symlink_path.empty());
437 DCHECK(!target_path.empty());
438 return ::symlink(target_path.value().c_str(),
439 symlink_path.value().c_str()) != -1;
440}
441
442bool ReadSymbolicLink(const FilePath& symlink_path,
443 FilePath* target_path) {
444 DCHECK(!symlink_path.empty());
445 DCHECK(target_path);
446 char buf[PATH_MAX];
447 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
448
[email protected]723571a2010-12-03 17:37:54449 if (count <= 0) {
450 target_path->clear();
[email protected]2e733d102010-11-30 00:43:37451 return false;
[email protected]723571a2010-12-03 17:37:54452 }
[email protected]2e733d102010-11-30 00:43:37453
454 *target_path = FilePath(FilePath::StringType(buf, count));
[email protected]2e733d102010-11-30 00:43:37455 return true;
456}
457
[email protected]9e51af92009-02-04 00:58:39458// Creates and opens a temporary file in |directory|, returning the
[email protected]16eac0a72009-09-11 17:33:50459// file descriptor. |path| is set to the temporary file path.
460// This function does NOT unlink() the file.
[email protected]9e51af92009-02-04 00:58:39461int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
[email protected]ba74b0d22010-10-23 05:19:20462 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
[email protected]151c4a62011-04-22 04:15:13463 *path = directory.Append(TempFileName());
[email protected]9e51af92009-02-04 00:58:39464 const std::string& tmpdir_string = path->value();
[email protected]778e8c52008-09-11 17:36:23465 // this should be OK since mkstemp just replaces characters in place
466 char* buffer = const_cast<char*>(tmpdir_string.c_str());
[email protected]392264c2008-11-11 00:01:38467
[email protected]b266ffea2011-04-12 06:07:25468 return HANDLE_EINTR(mkstemp(buffer));
[email protected]9e51af92009-02-04 00:58:39469}
470
[email protected]33edeab2009-08-18 16:07:55471bool CreateTemporaryFile(FilePath* path) {
[email protected]ba74b0d22010-10-23 05:19:20472 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]9e51af92009-02-04 00:58:39473 FilePath directory;
474 if (!GetTempDir(&directory))
475 return false;
476 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
[email protected]b2e97292008-09-02 18:20:34477 if (fd < 0)
478 return false;
[email protected]2e90bee2011-04-12 06:51:22479 ignore_result(HANDLE_EINTR(close(fd)));
[email protected]b2e97292008-09-02 18:20:34480 return true;
481}
482
[email protected]9e51af92009-02-04 00:58:39483FILE* CreateAndOpenTemporaryShmemFile(FilePath* path) {
484 FilePath directory;
485 if (!GetShmemTempDir(&directory))
[email protected]628476aa2010-06-10 22:56:23486 return NULL;
[email protected]9e51af92009-02-04 00:58:39487
[email protected]6faa0e0d2009-04-28 06:50:36488 return CreateAndOpenTemporaryFileInDir(directory, path);
489}
490
491FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
492 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
[email protected]9e51af92009-02-04 00:58:39493 if (fd < 0)
494 return NULL;
495
[email protected]139063bd2011-04-18 19:05:53496 FILE* file = fdopen(fd, "a+");
497 if (!file)
498 ignore_result(HANDLE_EINTR(close(fd)));
499 return file;
[email protected]9e51af92009-02-04 00:58:39500}
[email protected]6445c402009-09-11 20:06:27501
502bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
[email protected]ba74b0d22010-10-23 05:19:20503 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
[email protected]6445c402009-09-11 20:06:27504 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
[email protected]b266ffea2011-04-12 06:07:25505 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
[email protected]9ccbb372008-10-10 18:50:32506}
507
[email protected]b0b3abd92010-04-30 17:00:09508static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
509 const FilePath::StringType& name_tmpl,
510 FilePath* new_dir) {
[email protected]ba74b0d22010-10-23 05:19:20511 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
[email protected]b0b3abd92010-04-30 17:00:09512 CHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
513 << "Directory name template must contain \"XXXXXX\".";
514
515 FilePath sub_dir = base_dir.Append(name_tmpl);
516 std::string sub_dir_string = sub_dir.value();
517
518 // this should be OK since mkdtemp just replaces characters in place
519 char* buffer = const_cast<char*>(sub_dir_string.c_str());
520 char* dtemp = mkdtemp(buffer);
[email protected]3ad035d22010-07-28 21:00:51521 if (!dtemp) {
522 DPLOG(ERROR) << "mkdtemp";
[email protected]b0b3abd92010-04-30 17:00:09523 return false;
[email protected]3ad035d22010-07-28 21:00:51524 }
[email protected]b0b3abd92010-04-30 17:00:09525 *new_dir = FilePath(dtemp);
526 return true;
527}
528
529bool CreateTemporaryDirInDir(const FilePath& base_dir,
530 const FilePath::StringType& prefix,
[email protected]046062e82010-06-30 07:19:11531 FilePath* new_dir) {
[email protected]b0b3abd92010-04-30 17:00:09532 FilePath::StringType mkdtemp_template = prefix;
533 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
534 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
535}
536
[email protected]7e1fde6a2008-12-23 20:20:10537bool CreateNewTempDirectory(const FilePath::StringType& prefix,
538 FilePath* new_temp_path) {
[email protected]392264c2008-11-11 00:01:38539 FilePath tmpdir;
[email protected]b2e97292008-09-02 18:20:34540 if (!GetTempDir(&tmpdir))
541 return false;
[email protected]b0b3abd92010-04-30 17:00:09542
[email protected]151c4a62011-04-22 04:15:13543 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
[email protected]b2e97292008-09-02 18:20:34544}
545
[email protected]640517f2008-10-30 23:54:04546bool CreateDirectory(const FilePath& full_path) {
[email protected]ba74b0d22010-10-23 05:19:20547 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
[email protected]640517f2008-10-30 23:54:04548 std::vector<FilePath> subpaths;
549
550 // Collect a list of all parent directories.
551 FilePath last_path = full_path;
552 subpaths.push_back(full_path);
553 for (FilePath path = full_path.DirName();
554 path.value() != last_path.value(); path = path.DirName()) {
555 subpaths.push_back(path);
556 last_path = path;
557 }
558
559 // Iterate through the parents and create the missing ones.
560 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
561 i != subpaths.rend(); ++i) {
[email protected]0ba86e42010-03-17 21:39:42562 if (DirectoryExists(*i))
563 continue;
564 if (mkdir(i->value().c_str(), 0700) == 0)
565 continue;
566 // Mkdir failed, but it might have failed with EEXIST, or some other error
567 // due to the the directory appearing out of thin air. This can occur if
568 // two processes are trying to create the same file system tree at the same
569 // time. Check to see if it exists and make sure it is a directory.
570 if (!DirectoryExists(*i))
571 return false;
[email protected]b2e97292008-09-02 18:20:34572 }
573 return true;
574}
575
[email protected]cd78ad52011-05-31 23:10:06576// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
577// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
578bool IsLink(const FilePath& file_path) {
579 struct stat st;
580 // If we can't lstat the file, it's safe to assume that the file won't at
581 // least be a 'followable' link.
582 if (lstat(file_path.value().c_str(), &st) != 0)
583 return false;
584
585 if (S_ISLNK(st.st_mode))
586 return true;
587 else
588 return false;
589}
590
[email protected]2f0193c22010-09-03 02:28:37591bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
[email protected]fb66f9d2009-09-07 16:39:46592 stat_wrapper_t file_info;
593 if (CallStat(file_path.value().c_str(), &file_info) != 0)
[email protected]b2e97292008-09-02 18:20:34594 return false;
[email protected]f5e3da4d2008-09-26 01:04:08595 results->is_directory = S_ISDIR(file_info.st_mode);
596 results->size = file_info.st_size;
[email protected]5ef323892009-07-24 16:13:53597 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
[email protected]2f0193c22010-09-03 02:28:37598 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
599 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
[email protected]b2e97292008-09-02 18:20:34600 return true;
601}
602
[email protected]825003f2009-05-14 17:49:23603bool GetInode(const FilePath& path, ino_t* inode) {
[email protected]ba74b0d22010-10-23 05:19:20604 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
[email protected]825003f2009-05-14 17:49:23605 struct stat buffer;
606 int result = stat(path.value().c_str(), &buffer);
607 if (result < 0)
608 return false;
609
610 *inode = buffer.st_ino;
611 return true;
612}
613
[email protected]836f1342008-10-01 17:40:13614FILE* OpenFile(const std::string& filename, const char* mode) {
[email protected]a9cd2a652008-11-17 21:01:19615 return OpenFile(FilePath(filename), mode);
[email protected]836f1342008-10-01 17:40:13616}
617
[email protected]a9cd2a652008-11-17 21:01:19618FILE* OpenFile(const FilePath& filename, const char* mode) {
[email protected]ba74b0d22010-10-23 05:19:20619 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25620 FILE* result = NULL;
621 do {
622 result = fopen(filename.value().c_str(), mode);
623 } while (!result && errno == EINTR);
624 return result;
[email protected]836f1342008-10-01 17:40:13625}
626
[email protected]c870c762009-01-28 05:47:15627int ReadFile(const FilePath& filename, char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20628 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25629 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
[email protected]b2e97292008-09-02 18:20:34630 if (fd < 0)
631 return -1;
[email protected]a9cd2a652008-11-17 21:01:19632
[email protected]cabe39c2010-02-02 02:28:16633 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
634 if (int ret = HANDLE_EINTR(close(fd)) < 0)
635 return ret;
636 return bytes_read;
[email protected]b2e97292008-09-02 18:20:34637}
638
[email protected]c870c762009-01-28 05:47:15639int WriteFile(const FilePath& filename, const char* data, int size) {
[email protected]ba74b0d22010-10-23 05:19:20640 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25641 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
[email protected]b2e97292008-09-02 18:20:34642 if (fd < 0)
643 return -1;
[email protected]778e8c52008-09-11 17:36:23644
[email protected]cabe39c2010-02-02 02:28:16645 int bytes_written = WriteFileDescriptor(fd, data, size);
646 if (int ret = HANDLE_EINTR(close(fd)) < 0)
647 return ret;
648 return bytes_written;
[email protected]fbea0232009-09-16 00:29:22649}
650
651int WriteFileDescriptor(const int fd, const char* data, int size) {
652 // Allow for partial writes.
653 ssize_t bytes_written_total = 0;
654 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
655 bytes_written_total += bytes_written_partial) {
656 bytes_written_partial =
657 HANDLE_EINTR(write(fd, data + bytes_written_total,
658 size - bytes_written_total));
659 if (bytes_written_partial < 0)
660 return -1;
661 }
662
[email protected]778e8c52008-09-11 17:36:23663 return bytes_written_total;
[email protected]b2e97292008-09-02 18:20:34664}
665
666// Gets the current working directory for the process.
[email protected]640517f2008-10-30 23:54:04667bool GetCurrentDirectory(FilePath* dir) {
[email protected]ba74b0d22010-10-23 05:19:20668 // getcwd can return ENOENT, which implies it checks against the disk.
669 base::ThreadRestrictions::AssertIOAllowed();
670
[email protected]b2e97292008-09-02 18:20:34671 char system_buffer[PATH_MAX] = "";
[email protected]640517f2008-10-30 23:54:04672 if (!getcwd(system_buffer, sizeof(system_buffer))) {
673 NOTREACHED();
674 return false;
675 }
676 *dir = FilePath(system_buffer);
[email protected]b2e97292008-09-02 18:20:34677 return true;
678}
679
680// Sets the current working directory for the process.
[email protected]a9cd2a652008-11-17 21:01:19681bool SetCurrentDirectory(const FilePath& path) {
[email protected]ba74b0d22010-10-23 05:19:20682 base::ThreadRestrictions::AssertIOAllowed();
[email protected]a9cd2a652008-11-17 21:01:19683 int ret = chdir(path.value().c_str());
684 return !ret;
[email protected]b2e97292008-09-02 18:20:34685}
[email protected]a9cd2a652008-11-17 21:01:19686
[email protected]7856bb82008-12-12 23:43:03687///////////////////////////////////////////////
688// FileEnumerator
689
[email protected]0b733222008-12-11 14:55:12690FileEnumerator::FileEnumerator(const FilePath& root_path,
[email protected]b2e97292008-09-02 18:20:34691 bool recursive,
[email protected]58b7c5a62011-08-15 13:09:27692 FileType file_type)
[email protected]fbf745a2009-12-08 22:05:59693 : current_directory_entry_(0),
694 root_path_(root_path),
[email protected]49930c3a2009-08-06 21:23:07695 recursive_(recursive),
[email protected]a82026e2010-10-14 23:43:29696 file_type_(file_type) {
[email protected]8199b3a2009-06-09 05:57:38697 // INCLUDE_DOT_DOT must not be specified if recursive.
698 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
[email protected]b2e97292008-09-02 18:20:34699 pending_paths_.push(root_path);
700}
701
[email protected]0b733222008-12-11 14:55:12702FileEnumerator::FileEnumerator(const FilePath& root_path,
[email protected]b2e97292008-09-02 18:20:34703 bool recursive,
[email protected]58b7c5a62011-08-15 13:09:27704 FileType file_type,
[email protected]0b733222008-12-11 14:55:12705 const FilePath::StringType& pattern)
[email protected]fbf745a2009-12-08 22:05:59706 : current_directory_entry_(0),
707 root_path_(root_path),
[email protected]49930c3a2009-08-06 21:23:07708 recursive_(recursive),
[email protected]b2e97292008-09-02 18:20:34709 file_type_(file_type),
[email protected]a82026e2010-10-14 23:43:29710 pattern_(root_path.Append(pattern).value()) {
[email protected]8199b3a2009-06-09 05:57:38711 // INCLUDE_DOT_DOT must not be specified if recursive.
712 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
[email protected]49930c3a2009-08-06 21:23:07713 // The Windows version of this code appends the pattern to the root_path,
714 // potentially only matching against items in the top-most directory.
715 // Do the same here.
[email protected]f6b8ce32011-03-02 00:03:18716 if (pattern.empty())
[email protected]fbf745a2009-12-08 22:05:59717 pattern_ = FilePath::StringType();
[email protected]b2e97292008-09-02 18:20:34718 pending_paths_.push(root_path);
719}
[email protected]a9cd2a652008-11-17 21:01:19720
[email protected]b2e97292008-09-02 18:20:34721FileEnumerator::~FileEnumerator() {
[email protected]b2e97292008-09-02 18:20:34722}
723
[email protected]0b733222008-12-11 14:55:12724FilePath FileEnumerator::Next() {
[email protected]49930c3a2009-08-06 21:23:07725 ++current_directory_entry_;
726
727 // While we've exhausted the entries in the current directory, do the next
728 while (current_directory_entry_ >= directory_entries_.size()) {
[email protected]b2e97292008-09-02 18:20:34729 if (pending_paths_.empty())
[email protected]0b733222008-12-11 14:55:12730 return FilePath();
[email protected]13ef7c02008-11-20 22:30:13731
[email protected]b2e97292008-09-02 18:20:34732 root_path_ = pending_paths_.top();
[email protected]0b733222008-12-11 14:55:12733 root_path_ = root_path_.StripTrailingSeparators();
[email protected]b2e97292008-09-02 18:20:34734 pending_paths_.pop();
[email protected]13ef7c02008-11-20 22:30:13735
[email protected]49930c3a2009-08-06 21:23:07736 std::vector<DirectoryEntryInfo> entries;
737 if (!ReadDirectory(&entries, root_path_, file_type_ & SHOW_SYM_LINKS))
738 continue;
[email protected]13ef7c02008-11-20 22:30:13739
[email protected]49930c3a2009-08-06 21:23:07740 directory_entries_.clear();
741 current_directory_entry_ = 0;
742 for (std::vector<DirectoryEntryInfo>::const_iterator
743 i = entries.begin(); i != entries.end(); ++i) {
744 FilePath full_path = root_path_.Append(i->filename);
745 if (ShouldSkip(full_path))
746 continue;
[email protected]13ef7c02008-11-20 22:30:13747
[email protected]fbf745a2009-12-08 22:05:59748 if (pattern_.size() &&
749 fnmatch(pattern_.c_str(), full_path.value().c_str(), FNM_NOESCAPE))
[email protected]49930c3a2009-08-06 21:23:07750 continue;
751
752 if (recursive_ && S_ISDIR(i->stat.st_mode))
753 pending_paths_.push(full_path);
754
755 if ((S_ISDIR(i->stat.st_mode) && (file_type_ & DIRECTORIES)) ||
756 (!S_ISDIR(i->stat.st_mode) && (file_type_ & FILES)))
757 directory_entries_.push_back(*i);
[email protected]b2e97292008-09-02 18:20:34758 }
759 }
[email protected]13ef7c02008-11-20 22:30:13760
[email protected]49930c3a2009-08-06 21:23:07761 return root_path_.Append(directory_entries_[current_directory_entry_
762 ].filename);
763}
[email protected]8199b3a2009-06-09 05:57:38764
[email protected]eae9c062011-01-11 00:50:59765void FileEnumerator::GetFindInfo(FindInfo* info) {
766 DCHECK(info);
767
768 if (current_directory_entry_ >= directory_entries_.size())
769 return;
770
771 DirectoryEntryInfo* cur_entry = &directory_entries_[current_directory_entry_];
772 memcpy(&(info->stat), &(cur_entry->stat), sizeof(info->stat));
773 info->filename.assign(cur_entry->filename.value());
774}
775
776bool FileEnumerator::IsDirectory(const FindInfo& info) {
777 return S_ISDIR(info.stat.st_mode);
778}
779
780// static
781FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
782 return FilePath(find_info.filename);
783}
784
[email protected]f1ddaa42011-07-19 05:03:03785// static
786int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
787 return find_info.stat.st_size;
788}
789
790// static
791base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
792 return base::Time::FromTimeT(find_info.stat.st_mtime);
793}
794
[email protected]49930c3a2009-08-06 21:23:07795bool FileEnumerator::ReadDirectory(std::vector<DirectoryEntryInfo>* entries,
796 const FilePath& source, bool show_links) {
[email protected]ba74b0d22010-10-23 05:19:20797 base::ThreadRestrictions::AssertIOAllowed();
[email protected]49930c3a2009-08-06 21:23:07798 DIR* dir = opendir(source.value().c_str());
799 if (!dir)
800 return false;
801
[email protected]8d578822010-01-25 23:54:54802#if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_FREEBSD) && \
[email protected]f7d69972011-06-21 22:34:50803 !defined(OS_OPENBSD) && !defined(OS_SOLARIS) && !defined(OS_ANDROID)
[email protected]e43eddf12009-12-29 00:32:52804 #error Port warning: depending on the definition of struct dirent, \
805 additional space for pathname may be needed
[email protected]49930c3a2009-08-06 21:23:07806#endif
[email protected]e43eddf12009-12-29 00:32:52807
[email protected]49930c3a2009-08-06 21:23:07808 struct dirent dent_buf;
809 struct dirent* dent;
810 while (readdir_r(dir, &dent_buf, &dent) == 0 && dent) {
811 DirectoryEntryInfo info;
[email protected]49930c3a2009-08-06 21:23:07812 info.filename = FilePath(dent->d_name);
[email protected]2237f5d72009-09-03 22:39:34813
814 FilePath full_name = source.Append(dent->d_name);
815 int ret;
[email protected]49930c3a2009-08-06 21:23:07816 if (show_links)
[email protected]2237f5d72009-09-03 22:39:34817 ret = lstat(full_name.value().c_str(), &info.stat);
[email protected]49930c3a2009-08-06 21:23:07818 else
[email protected]2237f5d72009-09-03 22:39:34819 ret = stat(full_name.value().c_str(), &info.stat);
820 if (ret < 0) {
821 // Print the stat() error message unless it was ENOENT and we're
822 // following symlinks.
[email protected]e131cf52010-03-25 19:10:28823 if (!(errno == ENOENT && !show_links)) {
[email protected]57b765672009-10-13 18:27:40824 PLOG(ERROR) << "Couldn't stat "
825 << source.Append(dent->d_name).value();
[email protected]2237f5d72009-09-03 22:39:34826 }
[email protected]49930c3a2009-08-06 21:23:07827 memset(&info.stat, 0, sizeof(info.stat));
[email protected]8199b3a2009-06-09 05:57:38828 }
[email protected]49930c3a2009-08-06 21:23:07829 entries->push_back(info);
[email protected]b2e97292008-09-02 18:20:34830 }
[email protected]49930c3a2009-08-06 21:23:07831
832 closedir(dir);
833 return true;
834}
835
[email protected]7856bb82008-12-12 23:43:03836///////////////////////////////////////////////
837// MemoryMappedFile
838
839MemoryMappedFile::MemoryMappedFile()
[email protected]cb6037d2009-11-16 22:55:17840 : file_(base::kInvalidPlatformFileValue),
841 data_(NULL),
[email protected]7856bb82008-12-12 23:43:03842 length_(0) {
843}
844
[email protected]85c55dc2009-11-06 03:05:46845bool MemoryMappedFile::MapFileToMemoryInternal() {
[email protected]ba74b0d22010-10-23 05:19:20846 base::ThreadRestrictions::AssertIOAllowed();
847
[email protected]7856bb82008-12-12 23:43:03848 struct stat file_stat;
[email protected]cb6037d2009-11-16 22:55:17849 if (fstat(file_, &file_stat) == base::kInvalidPlatformFileValue) {
850 LOG(ERROR) << "Couldn't fstat " << file_ << ", errno " << errno;
[email protected]7856bb82008-12-12 23:43:03851 return false;
[email protected]4883a4e2009-06-06 19:59:36852 }
[email protected]7856bb82008-12-12 23:43:03853 length_ = file_stat.st_size;
854
855 data_ = static_cast<uint8*>(
[email protected]cb6037d2009-11-16 22:55:17856 mmap(NULL, length_, PROT_READ, MAP_SHARED, file_, 0));
[email protected]7856bb82008-12-12 23:43:03857 if (data_ == MAP_FAILED)
[email protected]cb6037d2009-11-16 22:55:17858 LOG(ERROR) << "Couldn't mmap " << file_ << ", errno " << errno;
[email protected]4883a4e2009-06-06 19:59:36859
860 return data_ != MAP_FAILED;
[email protected]7856bb82008-12-12 23:43:03861}
862
863void MemoryMappedFile::CloseHandles() {
[email protected]ba74b0d22010-10-23 05:19:20864 base::ThreadRestrictions::AssertIOAllowed();
865
[email protected]7856bb82008-12-12 23:43:03866 if (data_ != NULL)
867 munmap(data_, length_);
[email protected]cb6037d2009-11-16 22:55:17868 if (file_ != base::kInvalidPlatformFileValue)
[email protected]2e90bee2011-04-12 06:51:22869 ignore_result(HANDLE_EINTR(close(file_)));
[email protected]7856bb82008-12-12 23:43:03870
871 data_ = NULL;
872 length_ = 0;
[email protected]cb6037d2009-11-16 22:55:17873 file_ = base::kInvalidPlatformFileValue;
[email protected]7856bb82008-12-12 23:43:03874}
[email protected]13ef7c02008-11-20 22:30:13875
[email protected]35b9be02009-11-26 00:37:06876bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
877 const base::Time& cutoff_time) {
[email protected]e9ad4352010-11-17 11:19:15878 return static_cast<time_t>(find_info.stat.st_mtime) >= cutoff_time.ToTimeT();
[email protected]35b9be02009-11-26 00:37:06879}
880
[email protected]6f5f4322010-06-09 22:56:48881bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
882 FilePath real_path_result;
883 if (!RealPath(path, &real_path_result))
[email protected]01e2a1f2010-05-12 15:13:57884 return false;
885
[email protected]6f5f4322010-06-09 22:56:48886 // To be consistant with windows, fail if |real_path_result| is a
887 // directory.
888 stat_wrapper_t file_info;
889 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
890 S_ISDIR(file_info.st_mode))
891 return false;
892
893 *normalized_path = real_path_result;
[email protected]01e2a1f2010-05-12 15:13:57894 return true;
895}
896
[email protected]84cb1912010-04-21 21:11:36897#if !defined(OS_MACOSX)
898bool GetTempDir(FilePath* path) {
899 const char* tmp = getenv("TMPDIR");
900 if (tmp)
901 *path = FilePath(tmp);
902 else
[email protected]f7d69972011-06-21 22:34:50903#if defined(OS_ANDROID)
904 *path = FilePath("/data/local/tmp");
905#else
[email protected]84cb1912010-04-21 21:11:36906 *path = FilePath("/tmp");
[email protected]f7d69972011-06-21 22:34:50907#endif
[email protected]84cb1912010-04-21 21:11:36908 return true;
909}
910
[email protected]f7d69972011-06-21 22:34:50911#if !defined(OS_ANDROID)
[email protected]84cb1912010-04-21 21:11:36912bool GetShmemTempDir(FilePath* path) {
913 *path = FilePath("/dev/shm");
914 return true;
915}
[email protected]f7d69972011-06-21 22:34:50916#endif
[email protected]84cb1912010-04-21 21:11:36917
[email protected]1c657852010-04-22 23:28:05918FilePath GetHomeDir() {
919 const char* home_dir = getenv("HOME");
920 if (home_dir && home_dir[0])
921 return FilePath(home_dir);
922
[email protected]f7d69972011-06-21 22:34:50923#if defined(OS_ANDROID)
924 LOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
925#else
[email protected]ba74b0d22010-10-23 05:19:20926 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
927 base::ThreadRestrictions::AssertIOAllowed();
928
[email protected]1c657852010-04-22 23:28:05929 home_dir = g_get_home_dir();
930 if (home_dir && home_dir[0])
931 return FilePath(home_dir);
[email protected]f7d69972011-06-21 22:34:50932#endif
[email protected]1c657852010-04-22 23:28:05933
934 FilePath rv;
935 if (file_util::GetTempDir(&rv))
936 return rv;
937
938 // Last resort.
939 return FilePath("/tmp");
940}
941
[email protected]84cb1912010-04-21 21:11:36942bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
[email protected]ba74b0d22010-10-23 05:19:20943 base::ThreadRestrictions::AssertIOAllowed();
[email protected]b266ffea2011-04-12 06:07:25944 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
[email protected]84cb1912010-04-21 21:11:36945 if (infile < 0)
946 return false;
947
[email protected]b266ffea2011-04-12 06:07:25948 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
[email protected]84cb1912010-04-21 21:11:36949 if (outfile < 0) {
[email protected]2e90bee2011-04-12 06:51:22950 ignore_result(HANDLE_EINTR(close(infile)));
[email protected]84cb1912010-04-21 21:11:36951 return false;
952 }
953
954 const size_t kBufferSize = 32768;
955 std::vector<char> buffer(kBufferSize);
956 bool result = true;
957
958 while (result) {
959 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
960 if (bytes_read < 0) {
961 result = false;
962 break;
963 }
964 if (bytes_read == 0)
965 break;
966 // Allow for partial writes
967 ssize_t bytes_written_per_read = 0;
968 do {
969 ssize_t bytes_written_partial = HANDLE_EINTR(write(
970 outfile,
971 &buffer[bytes_written_per_read],
972 bytes_read - bytes_written_per_read));
973 if (bytes_written_partial < 0) {
974 result = false;
975 break;
976 }
977 bytes_written_per_read += bytes_written_partial;
978 } while (bytes_written_per_read < bytes_read);
979 }
980
981 if (HANDLE_EINTR(close(infile)) < 0)
982 result = false;
983 if (HANDLE_EINTR(close(outfile)) < 0)
984 result = false;
985
986 return result;
987}
988#endif // defined(OS_MACOSX)
989
[email protected]73e4c362011-09-22 14:47:18990bool VerifyPathControlledByUser(const FilePath& base,
991 const FilePath& path,
992 uid_t owner_uid,
993 gid_t group_gid) {
994 if (base != path && !base.IsParent(path)) {
995 LOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
996 << base.value() << "\", path = \"" << path.value() << "\"";
997 return false;
998 }
999
1000 std::vector<FilePath::StringType> base_components;
1001 std::vector<FilePath::StringType> path_components;
1002
1003 base.GetComponents(&base_components);
1004 path.GetComponents(&path_components);
1005
1006 std::vector<FilePath::StringType>::const_iterator ib, ip;
1007 for (ib = base_components.begin(), ip = path_components.begin();
1008 ib != base_components.end(); ++ib, ++ip) {
1009 // |base| must be a subpath of |path|, so all components should match.
1010 // If these CHECKs fail, look at the test that base is a parent of
1011 // path at the top of this function.
1012 CHECK(ip != path_components.end());
1013 CHECK(*ip == *ib);
1014 }
1015
1016 FilePath current_path = base;
1017 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gid))
1018 return false;
1019
1020 for (; ip != path_components.end(); ++ip) {
1021 current_path = current_path.Append(*ip);
1022 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gid))
1023 return false;
1024 }
1025 return true;
1026}
1027
1028#if defined(OS_MACOSX)
1029bool VerifyPathControlledByAdmin(const FilePath& path) {
1030 const unsigned kRootUid = 0;
1031 const FilePath kFileSystemRoot("/");
1032
1033 // The name of the administrator group on mac os.
1034 const char kAdminGroupName[] = "admin";
1035
1036 // Reading the groups database may touch the file system.
1037 base::ThreadRestrictions::AssertIOAllowed();
1038
1039 struct group *group_record = getgrnam(kAdminGroupName);
1040 if (!group_record) {
1041 PLOG(ERROR) << "Could not get the group ID of group \""
1042 << kAdminGroupName << "\".";
1043 return false;
1044 }
1045
1046 return VerifyPathControlledByUser(
1047 kFileSystemRoot, path, kRootUid, group_record->gr_gid);
1048}
1049#endif // defined(OS_MACOSX)
1050
[email protected]33e585a2010-11-20 03:38:151051} // namespace file_util