Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(101)

Side by Side Diff: base/files/file_util_posix.cc

Issue 1647803004: Move base to DEPS (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/files/file_util_mac.mm ('k') | base/files/file_util_proxy.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // 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/files/file_util.h"
6
7 #include <dirent.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <libgen.h>
11 #include <limits.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/mman.h>
16 #include <sys/param.h>
17 #include <sys/stat.h>
18 #include <sys/time.h>
19 #include <sys/types.h>
20 #include <time.h>
21 #include <unistd.h>
22
23 #if defined(OS_MACOSX)
24 #include <AvailabilityMacros.h>
25 #include "base/mac/foundation_util.h"
26 #elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
27 #include <glib.h> // for g_get_home_dir()
28 #endif
29
30 #include "base/basictypes.h"
31 #include "base/files/file_enumerator.h"
32 #include "base/files/file_path.h"
33 #include "base/files/scoped_file.h"
34 #include "base/logging.h"
35 #include "base/memory/scoped_ptr.h"
36 #include "base/memory/singleton.h"
37 #include "base/path_service.h"
38 #include "base/posix/eintr_wrapper.h"
39 #include "base/stl_util.h"
40 #include "base/strings/string_util.h"
41 #include "base/strings/stringprintf.h"
42 #include "base/strings/sys_string_conversions.h"
43 #include "base/strings/utf_string_conversions.h"
44 #include "base/sys_info.h"
45 #include "base/threading/thread_restrictions.h"
46 #include "base/time/time.h"
47
48 #if defined(OS_ANDROID)
49 #include "base/android/content_uri_utils.h"
50 #include "base/os_compat_android.h"
51 #endif
52
53 #if !defined(OS_IOS)
54 #include <grp.h>
55 #endif
56
57 namespace base {
58
59 namespace {
60
61 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
62 static int CallStat(const char *path, stat_wrapper_t *sb) {
63 ThreadRestrictions::AssertIOAllowed();
64 return stat(path, sb);
65 }
66 static int CallLstat(const char *path, stat_wrapper_t *sb) {
67 ThreadRestrictions::AssertIOAllowed();
68 return lstat(path, sb);
69 }
70 #else // defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
71 static int CallStat(const char *path, stat_wrapper_t *sb) {
72 ThreadRestrictions::AssertIOAllowed();
73 return stat64(path, sb);
74 }
75 static int CallLstat(const char *path, stat_wrapper_t *sb) {
76 ThreadRestrictions::AssertIOAllowed();
77 return lstat64(path, sb);
78 }
79 #endif // !(defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL))
80
81 #if !defined(OS_NACL_NONSFI)
82 // Helper for NormalizeFilePath(), defined below.
83 bool RealPath(const FilePath& path, FilePath* real_path) {
84 ThreadRestrictions::AssertIOAllowed(); // For realpath().
85 FilePath::CharType buf[PATH_MAX];
86 if (!realpath(path.value().c_str(), buf))
87 return false;
88
89 *real_path = FilePath(buf);
90 return true;
91 }
92
93 // Helper for VerifyPathControlledByUser.
94 bool VerifySpecificPathControlledByUser(const FilePath& path,
95 uid_t owner_uid,
96 const std::set<gid_t>& group_gids) {
97 stat_wrapper_t stat_info;
98 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
99 DPLOG(ERROR) << "Failed to get information on path "
100 << path.value();
101 return false;
102 }
103
104 if (S_ISLNK(stat_info.st_mode)) {
105 DLOG(ERROR) << "Path " << path.value()
106 << " is a symbolic link.";
107 return false;
108 }
109
110 if (stat_info.st_uid != owner_uid) {
111 DLOG(ERROR) << "Path " << path.value()
112 << " is owned by the wrong user.";
113 return false;
114 }
115
116 if ((stat_info.st_mode & S_IWGRP) &&
117 !ContainsKey(group_gids, stat_info.st_gid)) {
118 DLOG(ERROR) << "Path " << path.value()
119 << " is writable by an unprivileged group.";
120 return false;
121 }
122
123 if (stat_info.st_mode & S_IWOTH) {
124 DLOG(ERROR) << "Path " << path.value()
125 << " is writable by any user.";
126 return false;
127 }
128
129 return true;
130 }
131
132 std::string TempFileName() {
133 #if defined(OS_MACOSX)
134 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
135 #endif
136
137 #if defined(GOOGLE_CHROME_BUILD)
138 return std::string(".com.google.Chrome.XXXXXX");
139 #else
140 return std::string(".org.chromium.Chromium.XXXXXX");
141 #endif
142 }
143
144 // Creates and opens a temporary file in |directory|, returning the
145 // file descriptor. |path| is set to the temporary file path.
146 // This function does NOT unlink() the file.
147 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
148 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
149 *path = directory.Append(base::TempFileName());
150 const std::string& tmpdir_string = path->value();
151 // this should be OK since mkstemp just replaces characters in place
152 char* buffer = const_cast<char*>(tmpdir_string.c_str());
153
154 return HANDLE_EINTR(mkstemp(buffer));
155 }
156
157 #if defined(OS_LINUX)
158 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
159 // This depends on the mount options used for /dev/shm, which vary among
160 // different Linux distributions and possibly local configuration. It also
161 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
162 // but its kernel allows mprotect with PROT_EXEC anyway.
163 bool DetermineDevShmExecutable() {
164 bool result = false;
165 FilePath path;
166
167 ScopedFD fd(CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path));
168 if (fd.is_valid()) {
169 DeleteFile(path, false);
170 long sysconf_result = sysconf(_SC_PAGESIZE);
171 CHECK_GE(sysconf_result, 0);
172 size_t pagesize = static_cast<size_t>(sysconf_result);
173 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
174 void* mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd.get(), 0);
175 if (mapping != MAP_FAILED) {
176 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
177 result = true;
178 munmap(mapping, pagesize);
179 }
180 }
181 return result;
182 }
183 #endif // defined(OS_LINUX)
184 #endif // !defined(OS_NACL_NONSFI)
185
186 } // namespace
187
188 #if !defined(OS_NACL_NONSFI)
189 FilePath MakeAbsoluteFilePath(const FilePath& input) {
190 ThreadRestrictions::AssertIOAllowed();
191 char full_path[PATH_MAX];
192 if (realpath(input.value().c_str(), full_path) == NULL)
193 return FilePath();
194 return FilePath(full_path);
195 }
196
197 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
198 // which works both with and without the recursive flag. I'm not sure we need
199 // that functionality. If not, remove from file_util_win.cc, otherwise add it
200 // here.
201 bool DeleteFile(const FilePath& path, bool recursive) {
202 ThreadRestrictions::AssertIOAllowed();
203 const char* path_str = path.value().c_str();
204 stat_wrapper_t file_info;
205 int test = CallLstat(path_str, &file_info);
206 if (test != 0) {
207 // The Windows version defines this condition as success.
208 bool ret = (errno == ENOENT || errno == ENOTDIR);
209 return ret;
210 }
211 if (!S_ISDIR(file_info.st_mode))
212 return (unlink(path_str) == 0);
213 if (!recursive)
214 return (rmdir(path_str) == 0);
215
216 bool success = true;
217 std::stack<std::string> directories;
218 directories.push(path.value());
219 FileEnumerator traversal(path, true,
220 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
221 FileEnumerator::SHOW_SYM_LINKS);
222 for (FilePath current = traversal.Next(); success && !current.empty();
223 current = traversal.Next()) {
224 if (traversal.GetInfo().IsDirectory())
225 directories.push(current.value());
226 else
227 success = (unlink(current.value().c_str()) == 0);
228 }
229
230 while (success && !directories.empty()) {
231 FilePath dir = FilePath(directories.top());
232 directories.pop();
233 success = (rmdir(dir.value().c_str()) == 0);
234 }
235 return success;
236 }
237
238 bool ReplaceFile(const FilePath& from_path,
239 const FilePath& to_path,
240 File::Error* error) {
241 ThreadRestrictions::AssertIOAllowed();
242 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
243 return true;
244 if (error)
245 *error = File::OSErrorToFileError(errno);
246 return false;
247 }
248
249 bool CopyDirectory(const FilePath& from_path,
250 const FilePath& to_path,
251 bool recursive) {
252 ThreadRestrictions::AssertIOAllowed();
253 // Some old callers of CopyDirectory want it to support wildcards.
254 // After some discussion, we decided to fix those callers.
255 // Break loudly here if anyone tries to do this.
256 DCHECK(to_path.value().find('*') == std::string::npos);
257 DCHECK(from_path.value().find('*') == std::string::npos);
258
259 if (from_path.value().size() >= PATH_MAX) {
260 return false;
261 }
262
263 // This function does not properly handle destinations within the source
264 FilePath real_to_path = to_path;
265 if (PathExists(real_to_path)) {
266 real_to_path = MakeAbsoluteFilePath(real_to_path);
267 if (real_to_path.empty())
268 return false;
269 } else {
270 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
271 if (real_to_path.empty())
272 return false;
273 }
274 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
275 if (real_from_path.empty())
276 return false;
277 if (real_to_path.value().size() >= real_from_path.value().size() &&
278 real_to_path.value().compare(0, real_from_path.value().size(),
279 real_from_path.value()) == 0) {
280 return false;
281 }
282
283 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
284 if (recursive)
285 traverse_type |= FileEnumerator::DIRECTORIES;
286 FileEnumerator traversal(from_path, recursive, traverse_type);
287
288 // We have to mimic windows behavior here. |to_path| may not exist yet,
289 // start the loop with |to_path|.
290 struct stat from_stat;
291 FilePath current = from_path;
292 if (stat(from_path.value().c_str(), &from_stat) < 0) {
293 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
294 << from_path.value() << " errno = " << errno;
295 return false;
296 }
297 struct stat to_path_stat;
298 FilePath from_path_base = from_path;
299 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
300 S_ISDIR(to_path_stat.st_mode)) {
301 // If the destination already exists and is a directory, then the
302 // top level of source needs to be copied.
303 from_path_base = from_path.DirName();
304 }
305
306 // The Windows version of this function assumes that non-recursive calls
307 // will always have a directory for from_path.
308 // TODO(maruel): This is not necessary anymore.
309 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
310
311 bool success = true;
312 while (success && !current.empty()) {
313 // current is the source path, including from_path, so append
314 // the suffix after from_path to to_path to create the target_path.
315 FilePath target_path(to_path);
316 if (from_path_base != current) {
317 if (!from_path_base.AppendRelativePath(current, &target_path)) {
318 success = false;
319 break;
320 }
321 }
322
323 if (S_ISDIR(from_stat.st_mode)) {
324 if (mkdir(target_path.value().c_str(),
325 (from_stat.st_mode & 01777) | S_IRUSR | S_IXUSR | S_IWUSR) !=
326 0 &&
327 errno != EEXIST) {
328 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
329 << target_path.value() << " errno = " << errno;
330 success = false;
331 }
332 } else if (S_ISREG(from_stat.st_mode)) {
333 if (!CopyFile(current, target_path)) {
334 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
335 << target_path.value();
336 success = false;
337 }
338 } else {
339 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
340 << current.value();
341 }
342
343 current = traversal.Next();
344 if (!current.empty())
345 from_stat = traversal.GetInfo().stat();
346 }
347
348 return success;
349 }
350 #endif // !defined(OS_NACL_NONSFI)
351
352 bool PathExists(const FilePath& path) {
353 ThreadRestrictions::AssertIOAllowed();
354 #if defined(OS_ANDROID)
355 if (path.IsContentUri()) {
356 return ContentUriExists(path);
357 }
358 #endif
359 return access(path.value().c_str(), F_OK) == 0;
360 }
361
362 #if !defined(OS_NACL_NONSFI)
363 bool PathIsWritable(const FilePath& path) {
364 ThreadRestrictions::AssertIOAllowed();
365 return access(path.value().c_str(), W_OK) == 0;
366 }
367 #endif // !defined(OS_NACL_NONSFI)
368
369 bool DirectoryExists(const FilePath& path) {
370 ThreadRestrictions::AssertIOAllowed();
371 stat_wrapper_t file_info;
372 if (CallStat(path.value().c_str(), &file_info) == 0)
373 return S_ISDIR(file_info.st_mode);
374 return false;
375 }
376
377 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
378 size_t total_read = 0;
379 while (total_read < bytes) {
380 ssize_t bytes_read =
381 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
382 if (bytes_read <= 0)
383 break;
384 total_read += bytes_read;
385 }
386 return total_read == bytes;
387 }
388
389 #if !defined(OS_NACL_NONSFI)
390 bool CreateSymbolicLink(const FilePath& target_path,
391 const FilePath& symlink_path) {
392 DCHECK(!symlink_path.empty());
393 DCHECK(!target_path.empty());
394 return ::symlink(target_path.value().c_str(),
395 symlink_path.value().c_str()) != -1;
396 }
397
398 bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
399 DCHECK(!symlink_path.empty());
400 DCHECK(target_path);
401 char buf[PATH_MAX];
402 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
403
404 if (count <= 0) {
405 target_path->clear();
406 return false;
407 }
408
409 *target_path = FilePath(FilePath::StringType(buf, count));
410 return true;
411 }
412
413 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
414 ThreadRestrictions::AssertIOAllowed();
415 DCHECK(mode);
416
417 stat_wrapper_t file_info;
418 // Uses stat(), because on symbolic link, lstat() does not return valid
419 // permission bits in st_mode
420 if (CallStat(path.value().c_str(), &file_info) != 0)
421 return false;
422
423 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
424 return true;
425 }
426
427 bool SetPosixFilePermissions(const FilePath& path,
428 int mode) {
429 ThreadRestrictions::AssertIOAllowed();
430 DCHECK_EQ(mode & ~FILE_PERMISSION_MASK, 0);
431
432 // Calls stat() so that we can preserve the higher bits like S_ISGID.
433 stat_wrapper_t stat_buf;
434 if (CallStat(path.value().c_str(), &stat_buf) != 0)
435 return false;
436
437 // Clears the existing permission bits, and adds the new ones.
438 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
439 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
440
441 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
442 return false;
443
444 return true;
445 }
446
447 #if !defined(OS_MACOSX)
448 // This is implemented in file_util_mac.mm for Mac.
449 bool GetTempDir(FilePath* path) {
450 const char* tmp = getenv("TMPDIR");
451 if (tmp) {
452 *path = FilePath(tmp);
453 } else {
454 #if defined(OS_ANDROID)
455 return PathService::Get(base::DIR_CACHE, path);
456 #else
457 *path = FilePath("/tmp");
458 #endif
459 }
460 return true;
461 }
462 #endif // !defined(OS_MACOSX)
463
464 #if !defined(OS_MACOSX) // Mac implementation is in file_util_mac.mm.
465 FilePath GetHomeDir() {
466 #if defined(OS_CHROMEOS)
467 if (SysInfo::IsRunningOnChromeOS()) {
468 // On Chrome OS chrome::DIR_USER_DATA is overridden with a primary user
469 // homedir once it becomes available. Return / as the safe option.
470 return FilePath("/");
471 }
472 #endif
473
474 const char* home_dir = getenv("HOME");
475 if (home_dir && home_dir[0])
476 return FilePath(home_dir);
477
478 #if defined(OS_ANDROID)
479 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
480 #elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
481 // g_get_home_dir calls getpwent, which can fall through to LDAP calls so
482 // this may do I/O. However, it should be rare that $HOME is not defined and
483 // this is typically called from the path service which has no threading
484 // restrictions. The path service will cache the result which limits the
485 // badness of blocking on I/O. As a result, we don't have a thread
486 // restriction here.
487 home_dir = g_get_home_dir();
488 if (home_dir && home_dir[0])
489 return FilePath(home_dir);
490 #endif
491
492 FilePath rv;
493 if (GetTempDir(&rv))
494 return rv;
495
496 // Last resort.
497 return FilePath("/tmp");
498 }
499 #endif // !defined(OS_MACOSX)
500
501 bool CreateTemporaryFile(FilePath* path) {
502 ThreadRestrictions::AssertIOAllowed(); // For call to close().
503 FilePath directory;
504 if (!GetTempDir(&directory))
505 return false;
506 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
507 if (fd < 0)
508 return false;
509 close(fd);
510 return true;
511 }
512
513 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
514 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
515 if (fd < 0)
516 return NULL;
517
518 FILE* file = fdopen(fd, "a+");
519 if (!file)
520 close(fd);
521 return file;
522 }
523
524 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
525 ThreadRestrictions::AssertIOAllowed(); // For call to close().
526 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
527 return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
528 }
529
530 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
531 const FilePath::StringType& name_tmpl,
532 FilePath* new_dir) {
533 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
534 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
535 << "Directory name template must contain \"XXXXXX\".";
536
537 FilePath sub_dir = base_dir.Append(name_tmpl);
538 std::string sub_dir_string = sub_dir.value();
539
540 // this should be OK since mkdtemp just replaces characters in place
541 char* buffer = const_cast<char*>(sub_dir_string.c_str());
542 char* dtemp = mkdtemp(buffer);
543 if (!dtemp) {
544 DPLOG(ERROR) << "mkdtemp";
545 return false;
546 }
547 *new_dir = FilePath(dtemp);
548 return true;
549 }
550
551 bool CreateTemporaryDirInDir(const FilePath& base_dir,
552 const FilePath::StringType& prefix,
553 FilePath* new_dir) {
554 FilePath::StringType mkdtemp_template = prefix;
555 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
556 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
557 }
558
559 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
560 FilePath* new_temp_path) {
561 FilePath tmpdir;
562 if (!GetTempDir(&tmpdir))
563 return false;
564
565 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
566 }
567
568 bool CreateDirectoryAndGetError(const FilePath& full_path,
569 File::Error* error) {
570 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
571 std::vector<FilePath> subpaths;
572
573 // Collect a list of all parent directories.
574 FilePath last_path = full_path;
575 subpaths.push_back(full_path);
576 for (FilePath path = full_path.DirName();
577 path.value() != last_path.value(); path = path.DirName()) {
578 subpaths.push_back(path);
579 last_path = path;
580 }
581
582 // Iterate through the parents and create the missing ones.
583 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
584 i != subpaths.rend(); ++i) {
585 if (DirectoryExists(*i))
586 continue;
587 if (mkdir(i->value().c_str(), 0700) == 0)
588 continue;
589 // Mkdir failed, but it might have failed with EEXIST, or some other error
590 // due to the the directory appearing out of thin air. This can occur if
591 // two processes are trying to create the same file system tree at the same
592 // time. Check to see if it exists and make sure it is a directory.
593 int saved_errno = errno;
594 if (!DirectoryExists(*i)) {
595 if (error)
596 *error = File::OSErrorToFileError(saved_errno);
597 return false;
598 }
599 }
600 return true;
601 }
602
603 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
604 FilePath real_path_result;
605 if (!RealPath(path, &real_path_result))
606 return false;
607
608 // To be consistant with windows, fail if |real_path_result| is a
609 // directory.
610 stat_wrapper_t file_info;
611 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
612 S_ISDIR(file_info.st_mode))
613 return false;
614
615 *normalized_path = real_path_result;
616 return true;
617 }
618
619 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
620 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
621 bool IsLink(const FilePath& file_path) {
622 stat_wrapper_t st;
623 // If we can't lstat the file, it's safe to assume that the file won't at
624 // least be a 'followable' link.
625 if (CallLstat(file_path.value().c_str(), &st) != 0)
626 return false;
627
628 if (S_ISLNK(st.st_mode))
629 return true;
630 else
631 return false;
632 }
633
634 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
635 stat_wrapper_t file_info;
636 #if defined(OS_ANDROID)
637 if (file_path.IsContentUri()) {
638 File file = OpenContentUriForRead(file_path);
639 if (!file.IsValid())
640 return false;
641 return file.GetInfo(results);
642 } else {
643 #endif // defined(OS_ANDROID)
644 if (CallStat(file_path.value().c_str(), &file_info) != 0)
645 return false;
646 #if defined(OS_ANDROID)
647 }
648 #endif // defined(OS_ANDROID)
649
650 results->FromStat(file_info);
651 return true;
652 }
653 #endif // !defined(OS_NACL_NONSFI)
654
655 FILE* OpenFile(const FilePath& filename, const char* mode) {
656 ThreadRestrictions::AssertIOAllowed();
657 FILE* result = NULL;
658 do {
659 result = fopen(filename.value().c_str(), mode);
660 } while (!result && errno == EINTR);
661 return result;
662 }
663
664 // NaCl doesn't implement system calls to open files directly.
665 #if !defined(OS_NACL)
666 FILE* FileToFILE(File file, const char* mode) {
667 FILE* stream = fdopen(file.GetPlatformFile(), mode);
668 if (stream)
669 file.TakePlatformFile();
670 return stream;
671 }
672 #endif // !defined(OS_NACL)
673
674 int ReadFile(const FilePath& filename, char* data, int max_size) {
675 ThreadRestrictions::AssertIOAllowed();
676 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
677 if (fd < 0)
678 return -1;
679
680 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, max_size));
681 if (IGNORE_EINTR(close(fd)) < 0)
682 return -1;
683 return bytes_read;
684 }
685
686 int WriteFile(const FilePath& filename, const char* data, int size) {
687 ThreadRestrictions::AssertIOAllowed();
688 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0640));
689 if (fd < 0)
690 return -1;
691
692 int bytes_written = WriteFileDescriptor(fd, data, size) ? size : -1;
693 if (IGNORE_EINTR(close(fd)) < 0)
694 return -1;
695 return bytes_written;
696 }
697
698 bool WriteFileDescriptor(const int fd, const char* data, int size) {
699 // Allow for partial writes.
700 ssize_t bytes_written_total = 0;
701 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
702 bytes_written_total += bytes_written_partial) {
703 bytes_written_partial =
704 HANDLE_EINTR(write(fd, data + bytes_written_total,
705 size - bytes_written_total));
706 if (bytes_written_partial < 0)
707 return false;
708 }
709
710 return true;
711 }
712
713 #if !defined(OS_NACL_NONSFI)
714
715 bool AppendToFile(const FilePath& filename, const char* data, int size) {
716 ThreadRestrictions::AssertIOAllowed();
717 bool ret = true;
718 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
719 if (fd < 0) {
720 VPLOG(1) << "Unable to create file " << filename.value();
721 return false;
722 }
723
724 // This call will either write all of the data or return false.
725 if (!WriteFileDescriptor(fd, data, size)) {
726 VPLOG(1) << "Error while writing to file " << filename.value();
727 ret = false;
728 }
729
730 if (IGNORE_EINTR(close(fd)) < 0) {
731 VPLOG(1) << "Error while closing file " << filename.value();
732 return false;
733 }
734
735 return ret;
736 }
737
738 // Gets the current working directory for the process.
739 bool GetCurrentDirectory(FilePath* dir) {
740 // getcwd can return ENOENT, which implies it checks against the disk.
741 ThreadRestrictions::AssertIOAllowed();
742
743 char system_buffer[PATH_MAX] = "";
744 if (!getcwd(system_buffer, sizeof(system_buffer))) {
745 NOTREACHED();
746 return false;
747 }
748 *dir = FilePath(system_buffer);
749 return true;
750 }
751
752 // Sets the current working directory for the process.
753 bool SetCurrentDirectory(const FilePath& path) {
754 ThreadRestrictions::AssertIOAllowed();
755 int ret = chdir(path.value().c_str());
756 return !ret;
757 }
758
759 bool VerifyPathControlledByUser(const FilePath& base,
760 const FilePath& path,
761 uid_t owner_uid,
762 const std::set<gid_t>& group_gids) {
763 if (base != path && !base.IsParent(path)) {
764 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
765 << base.value() << "\", path = \"" << path.value() << "\"";
766 return false;
767 }
768
769 std::vector<FilePath::StringType> base_components;
770 std::vector<FilePath::StringType> path_components;
771
772 base.GetComponents(&base_components);
773 path.GetComponents(&path_components);
774
775 std::vector<FilePath::StringType>::const_iterator ib, ip;
776 for (ib = base_components.begin(), ip = path_components.begin();
777 ib != base_components.end(); ++ib, ++ip) {
778 // |base| must be a subpath of |path|, so all components should match.
779 // If these CHECKs fail, look at the test that base is a parent of
780 // path at the top of this function.
781 DCHECK(ip != path_components.end());
782 DCHECK(*ip == *ib);
783 }
784
785 FilePath current_path = base;
786 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
787 return false;
788
789 for (; ip != path_components.end(); ++ip) {
790 current_path = current_path.Append(*ip);
791 if (!VerifySpecificPathControlledByUser(
792 current_path, owner_uid, group_gids))
793 return false;
794 }
795 return true;
796 }
797
798 #if defined(OS_MACOSX) && !defined(OS_IOS)
799 bool VerifyPathControlledByAdmin(const FilePath& path) {
800 const unsigned kRootUid = 0;
801 const FilePath kFileSystemRoot("/");
802
803 // The name of the administrator group on mac os.
804 const char* const kAdminGroupNames[] = {
805 "admin",
806 "wheel"
807 };
808
809 // Reading the groups database may touch the file system.
810 ThreadRestrictions::AssertIOAllowed();
811
812 std::set<gid_t> allowed_group_ids;
813 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
814 struct group *group_record = getgrnam(kAdminGroupNames[i]);
815 if (!group_record) {
816 DPLOG(ERROR) << "Could not get the group ID of group \""
817 << kAdminGroupNames[i] << "\".";
818 continue;
819 }
820
821 allowed_group_ids.insert(group_record->gr_gid);
822 }
823
824 return VerifyPathControlledByUser(
825 kFileSystemRoot, path, kRootUid, allowed_group_ids);
826 }
827 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
828
829 int GetMaximumPathComponentLength(const FilePath& path) {
830 ThreadRestrictions::AssertIOAllowed();
831 return pathconf(path.value().c_str(), _PC_NAME_MAX);
832 }
833
834 #if !defined(OS_ANDROID)
835 // This is implemented in file_util_android.cc for that platform.
836 bool GetShmemTempDir(bool executable, FilePath* path) {
837 #if defined(OS_LINUX)
838 bool use_dev_shm = true;
839 if (executable) {
840 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
841 use_dev_shm = s_dev_shm_executable;
842 }
843 if (use_dev_shm) {
844 *path = FilePath("/dev/shm");
845 return true;
846 }
847 #endif
848 return GetTempDir(path);
849 }
850 #endif // !defined(OS_ANDROID)
851
852 #if !defined(OS_MACOSX)
853 // Mac has its own implementation, this is for all other Posix systems.
854 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
855 ThreadRestrictions::AssertIOAllowed();
856 File infile;
857 #if defined(OS_ANDROID)
858 if (from_path.IsContentUri()) {
859 infile = OpenContentUriForRead(from_path);
860 } else {
861 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
862 }
863 #else
864 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
865 #endif
866 if (!infile.IsValid())
867 return false;
868
869 File outfile(to_path, File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
870 if (!outfile.IsValid())
871 return false;
872
873 const size_t kBufferSize = 32768;
874 std::vector<char> buffer(kBufferSize);
875 bool result = true;
876
877 while (result) {
878 ssize_t bytes_read = infile.ReadAtCurrentPos(&buffer[0], buffer.size());
879 if (bytes_read < 0) {
880 result = false;
881 break;
882 }
883 if (bytes_read == 0)
884 break;
885 // Allow for partial writes
886 ssize_t bytes_written_per_read = 0;
887 do {
888 ssize_t bytes_written_partial = outfile.WriteAtCurrentPos(
889 &buffer[bytes_written_per_read], bytes_read - bytes_written_per_read);
890 if (bytes_written_partial < 0) {
891 result = false;
892 break;
893 }
894 bytes_written_per_read += bytes_written_partial;
895 } while (bytes_written_per_read < bytes_read);
896 }
897
898 return result;
899 }
900 #endif // !defined(OS_MACOSX)
901
902 // -----------------------------------------------------------------------------
903
904 namespace internal {
905
906 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
907 ThreadRestrictions::AssertIOAllowed();
908 // Windows compatibility: if to_path exists, from_path and to_path
909 // must be the same type, either both files, or both directories.
910 stat_wrapper_t to_file_info;
911 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
912 stat_wrapper_t from_file_info;
913 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
914 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
915 return false;
916 } else {
917 return false;
918 }
919 }
920
921 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
922 return true;
923
924 if (!CopyDirectory(from_path, to_path, true))
925 return false;
926
927 DeleteFile(from_path, true);
928 return true;
929 }
930
931 } // namespace internal
932
933 #endif // !defined(OS_NACL_NONSFI)
934 } // namespace base
OLDNEW
« no previous file with comments | « base/files/file_util_mac.mm ('k') | base/files/file_util_proxy.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698