1 // Copyright 2012 The Chromium Authors
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 <stddef.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/mman.h>
17 #include <sys/param.h>
18 #include <sys/time.h>
19 #include <sys/types.h>
20 #include <time.h>
21 #include <unistd.h>
22
23 #include <bit>
24 #include <optional>
25
26 #include "base/base_export.h"
27 #include "base/base_switches.h"
28 #include "base/bits.h"
29 #include "base/command_line.h"
30 #include "base/containers/adapters.h"
31 #include "base/containers/contains.h"
32 #include "base/containers/heap_array.h"
33 #include "base/containers/stack.h"
34 #include "base/environment.h"
35 #include "base/files/file_enumerator.h"
36 #include "base/files/file_path.h"
37 #include "base/files/scoped_file.h"
38 #include "base/logging.h"
39 #include "base/memory/singleton.h"
40 #include "base/notreached.h"
41 #include "base/numerics/safe_conversions.h"
42 #include "base/path_service.h"
43 #include "base/posix/eintr_wrapper.h"
44 #include "base/strings/strcat.h"
45 #include "base/strings/string_piece.h"
46 #include "base/strings/string_split.h"
47 #include "base/strings/string_util.h"
48 #include "base/strings/sys_string_conversions.h"
49 #include "base/strings/utf_string_conversions.h"
50 #include "base/system/sys_info.h"
51 #include "base/threading/scoped_blocking_call.h"
52 #include "base/time/time.h"
53 #include "build/branding_buildflags.h"
54 #include "build/build_config.h"
55
56 #if BUILDFLAG(IS_APPLE)
57 #include <AvailabilityMacros.h>
58 #include "base/apple/foundation_util.h"
59 #endif
60
61 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
62 #include <sys/sendfile.h>
63 #endif
64
65 #if BUILDFLAG(IS_ANDROID)
66 #include "base/android/content_uri_utils.h"
67 #include "base/os_compat_android.h"
68 #endif
69
70 #if !BUILDFLAG(IS_IOS)
71 #include <grp.h>
72 #endif
73
74 // We need to do this on AIX due to some inconsistencies in how AIX
75 // handles XOPEN_SOURCE and ALL_SOURCE.
76 #if BUILDFLAG(IS_AIX)
77 extern "C" char* mkdtemp(char* path);
78 #endif
79
80 namespace base {
81
82 namespace {
83
84 #if BUILDFLAG(IS_MAC)
85 // Helper for VerifyPathControlledByUser.
VerifySpecificPathControlledByUser(const FilePath & path,uid_t owner_uid,const std::set<gid_t> & group_gids)86 bool VerifySpecificPathControlledByUser(const FilePath& path,
87 uid_t owner_uid,
88 const std::set<gid_t>& group_gids) {
89 stat_wrapper_t stat_info;
90 if (File::Lstat(path.value().c_str(), &stat_info) != 0) {
91 DPLOG(ERROR) << "Failed to get information on path "
92 << path.value();
93 return false;
94 }
95
96 if (S_ISLNK(stat_info.st_mode)) {
97 DLOG(ERROR) << "Path " << path.value() << " is a symbolic link.";
98 return false;
99 }
100
101 if (stat_info.st_uid != owner_uid) {
102 DLOG(ERROR) << "Path " << path.value() << " is owned by the wrong user.";
103 return false;
104 }
105
106 if ((stat_info.st_mode & S_IWGRP) &&
107 !Contains(group_gids, stat_info.st_gid)) {
108 DLOG(ERROR) << "Path " << path.value()
109 << " is writable by an unprivileged group.";
110 return false;
111 }
112
113 if (stat_info.st_mode & S_IWOTH) {
114 DLOG(ERROR) << "Path " << path.value() << " is writable by any user.";
115 return false;
116 }
117
118 return true;
119 }
120 #endif
121
GetTempTemplate()122 base::FilePath GetTempTemplate() {
123 return FormatTemporaryFileName("XXXXXX");
124 }
125
AdvanceEnumeratorWithStat(FileEnumerator * traversal,FilePath * out_next_path,stat_wrapper_t * out_next_stat)126 bool AdvanceEnumeratorWithStat(FileEnumerator* traversal,
127 FilePath* out_next_path,
128 stat_wrapper_t* out_next_stat) {
129 DCHECK(out_next_path);
130 DCHECK(out_next_stat);
131 *out_next_path = traversal->Next();
132 if (out_next_path->empty())
133 return false;
134
135 *out_next_stat = traversal->GetInfo().stat();
136 return true;
137 }
138
DoCopyDirectory(const FilePath & from_path,const FilePath & to_path,bool recursive,bool open_exclusive)139 bool DoCopyDirectory(const FilePath& from_path,
140 const FilePath& to_path,
141 bool recursive,
142 bool open_exclusive) {
143 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
144 // Some old callers of CopyDirectory want it to support wildcards.
145 // After some discussion, we decided to fix those callers.
146 // Break loudly here if anyone tries to do this.
147 DCHECK(to_path.value().find('*') == std::string::npos);
148 DCHECK(from_path.value().find('*') == std::string::npos);
149
150 if (from_path.value().size() >= PATH_MAX) {
151 return false;
152 }
153
154 // This function does not properly handle destinations within the source
155 FilePath real_to_path = to_path;
156 if (PathExists(real_to_path))
157 real_to_path = MakeAbsoluteFilePath(real_to_path);
158 else
159 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
160 if (real_to_path.empty())
161 return false;
162
163 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
164 if (real_from_path.empty())
165 return false;
166 if (real_to_path == real_from_path || real_from_path.IsParent(real_to_path))
167 return false;
168
169 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
170 if (recursive)
171 traverse_type |= FileEnumerator::DIRECTORIES;
172 FileEnumerator traversal(from_path, recursive, traverse_type);
173
174 // We have to mimic windows behavior here. |to_path| may not exist yet,
175 // start the loop with |to_path|.
176 stat_wrapper_t from_stat;
177 FilePath current = from_path;
178 if (File::Stat(from_path.value().c_str(), &from_stat) < 0) {
179 DPLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
180 << from_path.value();
181 return false;
182 }
183 FilePath from_path_base = from_path;
184 if (recursive && DirectoryExists(to_path)) {
185 // If the destination already exists and is a directory, then the
186 // top level of source needs to be copied.
187 from_path_base = from_path.DirName();
188 }
189
190 // The Windows version of this function assumes that non-recursive calls
191 // will always have a directory for from_path.
192 // TODO(maruel): This is not necessary anymore.
193 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
194
195 do {
196 // current is the source path, including from_path, so append
197 // the suffix after from_path to to_path to create the target_path.
198 FilePath target_path(to_path);
199 if (from_path_base != current &&
200 !from_path_base.AppendRelativePath(current, &target_path)) {
201 return false;
202 }
203
204 if (S_ISDIR(from_stat.st_mode)) {
205 mode_t mode = (from_stat.st_mode & 01777) | S_IRUSR | S_IXUSR | S_IWUSR;
206 if (mkdir(target_path.value().c_str(), mode) == 0)
207 continue;
208 if (errno == EEXIST && !open_exclusive)
209 continue;
210
211 DPLOG(ERROR) << "CopyDirectory() couldn't create directory: "
212 << target_path.value();
213 return false;
214 }
215
216 if (!S_ISREG(from_stat.st_mode)) {
217 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
218 << current.value();
219 continue;
220 }
221
222 // Add O_NONBLOCK so we can't block opening a pipe.
223 File infile(open(current.value().c_str(), O_RDONLY | O_NONBLOCK));
224 if (!infile.IsValid()) {
225 DPLOG(ERROR) << "CopyDirectory() couldn't open file: " << current.value();
226 return false;
227 }
228
229 stat_wrapper_t stat_at_use;
230 if (File::Fstat(infile.GetPlatformFile(), &stat_at_use) < 0) {
231 DPLOG(ERROR) << "CopyDirectory() couldn't stat file: " << current.value();
232 return false;
233 }
234
235 if (!S_ISREG(stat_at_use.st_mode)) {
236 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
237 << current.value();
238 continue;
239 }
240
241 int open_flags = O_WRONLY | O_CREAT;
242 // If |open_exclusive| is set then we should always create the destination
243 // file, so O_NONBLOCK is not necessary to ensure we don't block on the
244 // open call for the target file below, and since the destination will
245 // always be a regular file it wouldn't affect the behavior of the
246 // subsequent write calls anyway.
247 if (open_exclusive)
248 open_flags |= O_EXCL;
249 else
250 open_flags |= O_TRUNC | O_NONBLOCK;
251 // Each platform has different default file opening modes for CopyFile which
252 // we want to replicate here. On OS X, we use copyfile(3) which takes the
253 // source file's permissions into account. On the other platforms, we just
254 // use the base::File constructor. On Chrome OS, base::File uses a different
255 // set of permissions than it does on other POSIX platforms.
256 #if BUILDFLAG(IS_APPLE)
257 mode_t mode = 0600 | (stat_at_use.st_mode & 0177);
258 #elif BUILDFLAG(IS_CHROMEOS)
259 mode_t mode = 0644;
260 #else
261 mode_t mode = 0600;
262 #endif
263 File outfile(open(target_path.value().c_str(), open_flags, mode));
264 if (!outfile.IsValid()) {
265 DPLOG(ERROR) << "CopyDirectory() couldn't create file: "
266 << target_path.value();
267 return false;
268 }
269
270 if (!CopyFileContents(infile, outfile)) {
271 DLOG(ERROR) << "CopyDirectory() couldn't copy file: " << current.value();
272 return false;
273 }
274 } while (AdvanceEnumeratorWithStat(&traversal, ¤t, &from_stat));
275
276 return true;
277 }
278
279 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
280 // which works both with and without the recursive flag. I'm not sure we need
281 // that functionality. If not, remove from file_util_win.cc, otherwise add it
282 // here.
DoDeleteFile(const FilePath & path,bool recursive)283 bool DoDeleteFile(const FilePath& path, bool recursive) {
284 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
285
286 #if BUILDFLAG(IS_ANDROID)
287 if (path.IsContentUri())
288 return DeleteContentUri(path);
289 #endif // BUILDFLAG(IS_ANDROID)
290
291 const char* path_str = path.value().c_str();
292 stat_wrapper_t file_info;
293 if (File::Lstat(path_str, &file_info) != 0) {
294 // The Windows version defines this condition as success.
295 return (errno == ENOENT);
296 }
297 if (!S_ISDIR(file_info.st_mode))
298 return (unlink(path_str) == 0) || (errno == ENOENT);
299 if (!recursive)
300 return (rmdir(path_str) == 0) || (errno == ENOENT);
301
302 bool success = true;
303 stack<std::string> directories;
304 directories.push(path.value());
305 FileEnumerator traversal(path, true,
306 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
307 FileEnumerator::SHOW_SYM_LINKS);
308 for (FilePath current = traversal.Next(); !current.empty();
309 current = traversal.Next()) {
310 if (traversal.GetInfo().IsDirectory())
311 directories.push(current.value());
312 else
313 success &= (unlink(current.value().c_str()) == 0) || (errno == ENOENT);
314 }
315
316 while (!directories.empty()) {
317 FilePath dir = FilePath(directories.top());
318 directories.pop();
319 success &= (rmdir(dir.value().c_str()) == 0) || (errno == ENOENT);
320 }
321 return success;
322 }
323
324 #if !BUILDFLAG(IS_APPLE)
325 // Appends |mode_char| to |mode| before the optional character set encoding; see
326 // https://www.gnu.org/software/libc/manual/html_node/Opening-Streams.html for
327 // details.
AppendModeCharacter(StringPiece mode,char mode_char)328 std::string AppendModeCharacter(StringPiece mode, char mode_char) {
329 std::string result(mode);
330 size_t comma_pos = result.find(',');
331 result.insert(comma_pos == std::string::npos ? result.length() : comma_pos, 1,
332 mode_char);
333 return result;
334 }
335 #endif
336
337 #if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_APPLE) && \
338 !(BUILDFLAG(IS_ANDROID) && __ANDROID_API__ >= 21)
PreReadFileSlow(const FilePath & file_path,int64_t max_bytes)339 bool PreReadFileSlow(const FilePath& file_path, int64_t max_bytes) {
340 DCHECK_GE(max_bytes, 0);
341
342 File file(file_path, File::FLAG_OPEN | File::FLAG_READ);
343 if (!file.IsValid()) {
344 return false;
345 }
346
347 constexpr size_t kBufferSize = 1024 * 1024;
348 auto buffer = base::HeapArray<uint8_t>::Uninit(kBufferSize);
349
350 while (max_bytes > 0) {
351 const size_t read_size = base::checked_cast<size_t>(
352 std::min<uint64_t>(static_cast<uint64_t>(max_bytes), buffer.size()));
353 std::optional<size_t> read_bytes =
354 file.ReadAtCurrentPos(buffer.first(read_size));
355 if (!read_bytes.has_value()) {
356 return false;
357 }
358 if (read_bytes.value() == 0) {
359 break;
360 }
361 max_bytes -= read_bytes.value();
362 }
363
364 return true;
365 }
366 #endif
367
368 } // namespace
369
MakeAbsoluteFilePath(const FilePath & input)370 FilePath MakeAbsoluteFilePath(const FilePath& input) {
371 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
372 char full_path[PATH_MAX];
373 if (realpath(input.value().c_str(), full_path) == nullptr)
374 return FilePath();
375 return FilePath(full_path);
376 }
377
MakeAbsoluteFilePathNoResolveSymbolicLinks(const FilePath & input)378 std::optional<FilePath> MakeAbsoluteFilePathNoResolveSymbolicLinks(
379 const FilePath& input) {
380 if (input.empty()) {
381 return std::nullopt;
382 }
383
384 FilePath collapsed_path;
385 std::vector<FilePath::StringType> components = input.GetComponents();
386 base::span<FilePath::StringType> components_span(components);
387 // Start with root for absolute |input| and the current working directory for
388 // a relative |input|.
389 if (input.IsAbsolute()) {
390 collapsed_path = FilePath(components_span[0]);
391 components_span = components_span.subspan(1);
392 } else {
393 if (!GetCurrentDirectory(&collapsed_path)) {
394 return std::nullopt;
395 }
396 }
397
398 for (const auto& component : components_span) {
399 if (component == FilePath::kCurrentDirectory) {
400 continue;
401 }
402
403 if (component == FilePath::kParentDirectory) {
404 // Pop the most recent component off the FilePath. Works correctly when
405 // the FilePath is root.
406 collapsed_path = collapsed_path.DirName();
407 continue;
408 }
409
410 // This is just a regular component. Append it.
411 collapsed_path = collapsed_path.Append(component);
412 }
413
414 return collapsed_path;
415 }
416
DeleteFile(const FilePath & path)417 bool DeleteFile(const FilePath& path) {
418 return DoDeleteFile(path, /*recursive=*/false);
419 }
420
DeletePathRecursively(const FilePath & path)421 bool DeletePathRecursively(const FilePath& path) {
422 return DoDeleteFile(path, /*recursive=*/true);
423 }
424
ReplaceFile(const FilePath & from_path,const FilePath & to_path,File::Error * error)425 bool ReplaceFile(const FilePath& from_path,
426 const FilePath& to_path,
427 File::Error* error) {
428 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
429 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
430 return true;
431 if (error)
432 *error = File::GetLastFileError();
433 return false;
434 }
435
CopyDirectory(const FilePath & from_path,const FilePath & to_path,bool recursive)436 bool CopyDirectory(const FilePath& from_path,
437 const FilePath& to_path,
438 bool recursive) {
439 return DoCopyDirectory(from_path, to_path, recursive, false);
440 }
441
CopyDirectoryExcl(const FilePath & from_path,const FilePath & to_path,bool recursive)442 bool CopyDirectoryExcl(const FilePath& from_path,
443 const FilePath& to_path,
444 bool recursive) {
445 return DoCopyDirectory(from_path, to_path, recursive, true);
446 }
447
CreatePipe(ScopedFD * read_fd,ScopedFD * write_fd,bool non_blocking)448 bool CreatePipe(ScopedFD* read_fd, ScopedFD* write_fd, bool non_blocking) {
449 int fds[2];
450 bool created =
451 non_blocking ? CreateLocalNonBlockingPipe(fds) : (0 == pipe(fds));
452 if (!created)
453 return false;
454 read_fd->reset(fds[0]);
455 write_fd->reset(fds[1]);
456 return true;
457 }
458
CreateLocalNonBlockingPipe(int fds[2])459 bool CreateLocalNonBlockingPipe(int fds[2]) {
460 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
461 return pipe2(fds, O_CLOEXEC | O_NONBLOCK) == 0;
462 #else
463 int raw_fds[2];
464 if (pipe(raw_fds) != 0)
465 return false;
466 ScopedFD fd_out(raw_fds[0]);
467 ScopedFD fd_in(raw_fds[1]);
468 if (!SetCloseOnExec(fd_out.get()))
469 return false;
470 if (!SetCloseOnExec(fd_in.get()))
471 return false;
472 if (!SetNonBlocking(fd_out.get()))
473 return false;
474 if (!SetNonBlocking(fd_in.get()))
475 return false;
476 fds[0] = fd_out.release();
477 fds[1] = fd_in.release();
478 return true;
479 #endif
480 }
481
SetNonBlocking(int fd)482 bool SetNonBlocking(int fd) {
483 const int flags = fcntl(fd, F_GETFL);
484 if (flags == -1)
485 return false;
486 if (flags & O_NONBLOCK)
487 return true;
488 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
489 return false;
490 }
491 return true;
492 }
493
SetCloseOnExec(int fd)494 bool SetCloseOnExec(int fd) {
495 const int flags = fcntl(fd, F_GETFD);
496 if (flags == -1)
497 return false;
498 if (flags & FD_CLOEXEC)
499 return true;
500 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
501 return false;
502 }
503 return true;
504 }
505
RemoveCloseOnExec(int fd)506 bool RemoveCloseOnExec(int fd) {
507 const int flags = fcntl(fd, F_GETFD);
508 if (flags == -1) {
509 return false;
510 }
511 if ((flags & FD_CLOEXEC) == 0) {
512 return true;
513 }
514 if (fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) == -1) {
515 return false;
516 }
517 return true;
518 }
519
PathExists(const FilePath & path)520 bool PathExists(const FilePath& path) {
521 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
522 #if BUILDFLAG(IS_ANDROID)
523 if (path.IsContentUri()) {
524 return ContentUriExists(path);
525 }
526 #endif
527 return access(path.value().c_str(), F_OK) == 0;
528 }
529
PathIsReadable(const FilePath & path)530 bool PathIsReadable(const FilePath& path) {
531 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
532 return access(path.value().c_str(), R_OK) == 0;
533 }
534
PathIsWritable(const FilePath & path)535 bool PathIsWritable(const FilePath& path) {
536 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
537 return access(path.value().c_str(), W_OK) == 0;
538 }
539
DirectoryExists(const FilePath & path)540 bool DirectoryExists(const FilePath& path) {
541 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
542 stat_wrapper_t file_info;
543 if (File::Stat(path.value().c_str(), &file_info) != 0)
544 return false;
545 return S_ISDIR(file_info.st_mode);
546 }
547
ReadFromFD(int fd,span<char> buffer)548 bool ReadFromFD(int fd, span<char> buffer) {
549 while (!buffer.empty()) {
550 ssize_t bytes_read = HANDLE_EINTR(read(fd, buffer.data(), buffer.size()));
551
552 if (bytes_read <= 0) {
553 return false;
554 }
555 buffer = buffer.subspan(static_cast<size_t>(bytes_read));
556 }
557 return true;
558 }
559
ReadFromFD(int fd,char * buffer,size_t bytes)560 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
561 return ReadFromFD(fd, make_span(buffer, bytes));
562 }
563
CreateAndOpenFdForTemporaryFileInDir(const FilePath & directory,FilePath * path)564 ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& directory,
565 FilePath* path) {
566 ScopedBlockingCall scoped_blocking_call(
567 FROM_HERE,
568 BlockingType::MAY_BLOCK); // For call to mkstemp().
569 *path = directory.Append(GetTempTemplate());
570 const std::string& tmpdir_string = path->value();
571 // this should be OK since mkstemp just replaces characters in place
572 char* buffer = const_cast<char*>(tmpdir_string.c_str());
573
574 return ScopedFD(HANDLE_EINTR(mkstemp(buffer)));
575 }
576
577 #if !BUILDFLAG(IS_FUCHSIA)
CreateSymbolicLink(const FilePath & target_path,const FilePath & symlink_path)578 bool CreateSymbolicLink(const FilePath& target_path,
579 const FilePath& symlink_path) {
580 DCHECK(!symlink_path.empty());
581 DCHECK(!target_path.empty());
582 return ::symlink(target_path.value().c_str(),
583 symlink_path.value().c_str()) != -1;
584 }
585
ReadSymbolicLink(const FilePath & symlink_path,FilePath * target_path)586 bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
587 DCHECK(!symlink_path.empty());
588 DCHECK(target_path);
589 char buf[PATH_MAX];
590 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, std::size(buf));
591
592 #if BUILDFLAG(IS_ANDROID) && defined(__LP64__)
593 // A few 64-bit Android L/M devices return INT_MAX instead of -1 here for
594 // errors; this is related to bionic's (incorrect) definition of ssize_t as
595 // being long int instead of int. Cast it so the compiler generates the
596 // comparison we want here. https://crbug.com/1101940
597 bool error = static_cast<int32_t>(count) <= 0;
598 #else
599 bool error = count <= 0;
600 #endif
601
602 if (error) {
603 target_path->clear();
604 return false;
605 }
606
607 *target_path =
608 FilePath(FilePath::StringType(buf, static_cast<size_t>(count)));
609 return true;
610 }
611
ReadSymbolicLinkAbsolute(const FilePath & symlink_path)612 std::optional<FilePath> ReadSymbolicLinkAbsolute(const FilePath& symlink_path) {
613 FilePath target_path;
614 if (!ReadSymbolicLink(symlink_path, &target_path)) {
615 return std::nullopt;
616 }
617
618 // Relative symbolic links are relative to the symlink's directory.
619 if (!target_path.IsAbsolute()) {
620 target_path = symlink_path.DirName().Append(target_path);
621 }
622
623 // Remove "/./" and "/../" to make this more friendly to path-allowlist-based
624 // sandboxes.
625 return MakeAbsoluteFilePathNoResolveSymbolicLinks(target_path);
626 }
627
GetPosixFilePermissions(const FilePath & path,int * mode)628 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
629 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
630 DCHECK(mode);
631
632 stat_wrapper_t file_info;
633 // Uses stat(), because on symbolic link, lstat() does not return valid
634 // permission bits in st_mode
635 if (File::Stat(path.value().c_str(), &file_info) != 0)
636 return false;
637
638 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
639 return true;
640 }
641
SetPosixFilePermissions(const FilePath & path,int mode)642 bool SetPosixFilePermissions(const FilePath& path,
643 int mode) {
644 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
645 DCHECK_EQ(mode & ~FILE_PERMISSION_MASK, 0);
646
647 // Calls stat() so that we can preserve the higher bits like S_ISGID.
648 stat_wrapper_t stat_buf;
649 if (File::Stat(path.value().c_str(), &stat_buf) != 0)
650 return false;
651
652 // Clears the existing permission bits, and adds the new ones.
653 // The casting here is because the Android NDK does not declare `st_mode` as a
654 // `mode_t`.
655 mode_t updated_mode_bits = static_cast<mode_t>(stat_buf.st_mode);
656 updated_mode_bits &= static_cast<mode_t>(~FILE_PERMISSION_MASK);
657 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
658
659 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
660 return false;
661
662 return true;
663 }
664
ExecutableExistsInPath(Environment * env,const FilePath::StringType & executable)665 bool ExecutableExistsInPath(Environment* env,
666 const FilePath::StringType& executable) {
667 std::string path;
668 if (!env->GetVar("PATH", &path)) {
669 LOG(ERROR) << "No $PATH variable. Assuming no " << executable << ".";
670 return false;
671 }
672
673 for (const StringPiece& cur_path :
674 SplitStringPiece(path, ":", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
675 FilePath file(cur_path);
676 int permissions;
677 if (GetPosixFilePermissions(file.Append(executable), &permissions) &&
678 (permissions & FILE_PERMISSION_EXECUTE_BY_USER))
679 return true;
680 }
681 return false;
682 }
683
684 #endif // !BUILDFLAG(IS_FUCHSIA)
685
686 #if !BUILDFLAG(IS_APPLE)
687 // This is implemented in file_util_apple.mm for Mac.
GetTempDir(FilePath * path)688 bool GetTempDir(FilePath* path) {
689 const char* tmp = getenv("TMPDIR");
690 if (tmp) {
691 *path = FilePath(tmp);
692 return true;
693 }
694
695 #if BUILDFLAG(IS_ANDROID)
696 return PathService::Get(DIR_CACHE, path);
697 #else
698 *path = FilePath("/tmp");
699 return true;
700 #endif
701 }
702 #endif // !BUILDFLAG(IS_APPLE)
703
704 #if !BUILDFLAG(IS_APPLE) // Mac implementation is in file_util_apple.mm.
GetHomeDir()705 FilePath GetHomeDir() {
706 #if BUILDFLAG(IS_CHROMEOS)
707 if (SysInfo::IsRunningOnChromeOS()) {
708 // On Chrome OS chrome::DIR_USER_DATA is overridden with a primary user
709 // homedir once it becomes available. Return / as the safe option.
710 return FilePath("/");
711 }
712 #endif
713
714 const char* home_dir = getenv("HOME");
715 if (home_dir && home_dir[0])
716 return FilePath(home_dir);
717
718 #if BUILDFLAG(IS_ANDROID)
719 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
720 #endif
721
722 FilePath rv;
723 if (GetTempDir(&rv))
724 return rv;
725
726 // Last resort.
727 return FilePath("/tmp");
728 }
729 #endif // !BUILDFLAG(IS_APPLE)
730
CreateAndOpenTemporaryFileInDir(const FilePath & dir,FilePath * temp_file)731 File CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
732 // For call to close() inside ScopedFD.
733 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
734 ScopedFD fd = CreateAndOpenFdForTemporaryFileInDir(dir, temp_file);
735 return fd.is_valid() ? File(std::move(fd)) : File(File::GetLastFileError());
736 }
737
CreateTemporaryFileInDir(const FilePath & dir,FilePath * temp_file)738 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
739 // For call to close() inside ScopedFD.
740 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
741 ScopedFD fd = CreateAndOpenFdForTemporaryFileInDir(dir, temp_file);
742 return fd.is_valid();
743 }
744
FormatTemporaryFileName(FilePath::StringPieceType identifier)745 FilePath FormatTemporaryFileName(FilePath::StringPieceType identifier) {
746 #if BUILDFLAG(IS_APPLE)
747 StringPiece prefix = base::apple::BaseBundleID();
748 #elif BUILDFLAG(GOOGLE_CHROME_BRANDING)
749 StringPiece prefix = "com.google.Chrome";
750 #else
751 StringPiece prefix = "org.chromium.Chromium";
752 #endif
753 return FilePath(StrCat({".", prefix, ".", identifier}));
754 }
755
CreateAndOpenTemporaryStreamInDir(const FilePath & dir,FilePath * path)756 ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
757 FilePath* path) {
758 ScopedFD scoped_fd = CreateAndOpenFdForTemporaryFileInDir(dir, path);
759 if (!scoped_fd.is_valid())
760 return nullptr;
761
762 int fd = scoped_fd.release();
763 FILE* file = fdopen(fd, "a+");
764 if (!file)
765 close(fd);
766 return ScopedFILE(file);
767 }
768
CreateTemporaryDirInDirImpl(const FilePath & base_dir,const FilePath & name_tmpl,FilePath * new_dir)769 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
770 const FilePath& name_tmpl,
771 FilePath* new_dir) {
772 ScopedBlockingCall scoped_blocking_call(
773 FROM_HERE, BlockingType::MAY_BLOCK); // For call to mkdtemp().
774 DCHECK(EndsWith(name_tmpl.value(), "XXXXXX"))
775 << "Directory name template must end with \"XXXXXX\".";
776
777 FilePath sub_dir = base_dir.Append(name_tmpl);
778 std::string sub_dir_string = sub_dir.value();
779
780 // this should be OK since mkdtemp just replaces characters in place
781 char* buffer = const_cast<char*>(sub_dir_string.c_str());
782 char* dtemp = mkdtemp(buffer);
783 if (!dtemp) {
784 DPLOG(ERROR) << "mkdtemp";
785 return false;
786 }
787 *new_dir = FilePath(dtemp);
788 return true;
789 }
790
CreateTemporaryDirInDir(const FilePath & base_dir,const FilePath::StringType & prefix,FilePath * new_dir)791 bool CreateTemporaryDirInDir(const FilePath& base_dir,
792 const FilePath::StringType& prefix,
793 FilePath* new_dir) {
794 FilePath::StringType mkdtemp_template = prefix;
795 mkdtemp_template.append("XXXXXX");
796 return CreateTemporaryDirInDirImpl(base_dir, FilePath(mkdtemp_template),
797 new_dir);
798 }
799
CreateNewTempDirectory(const FilePath::StringType & prefix,FilePath * new_temp_path)800 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
801 FilePath* new_temp_path) {
802 FilePath tmpdir;
803 if (!GetTempDir(&tmpdir))
804 return false;
805
806 return CreateTemporaryDirInDirImpl(tmpdir, GetTempTemplate(), new_temp_path);
807 }
808
CreateDirectoryAndGetError(const FilePath & full_path,File::Error * error)809 bool CreateDirectoryAndGetError(const FilePath& full_path,
810 File::Error* error) {
811 ScopedBlockingCall scoped_blocking_call(
812 FROM_HERE, BlockingType::MAY_BLOCK); // For call to mkdir().
813 std::vector<FilePath> subpaths;
814
815 // Collect a list of all parent directories.
816 FilePath last_path = full_path;
817 subpaths.push_back(full_path);
818 for (FilePath path = full_path.DirName();
819 path.value() != last_path.value(); path = path.DirName()) {
820 subpaths.push_back(path);
821 last_path = path;
822 }
823
824 // Iterate through the parents and create the missing ones.
825 for (const FilePath& subpath : base::Reversed(subpaths)) {
826 if (DirectoryExists(subpath))
827 continue;
828 if (mkdir(subpath.value().c_str(), 0700) == 0)
829 continue;
830 // Mkdir failed, but it might have failed with EEXIST, or some other error
831 // due to the directory appearing out of thin air. This can occur if
832 // two processes are trying to create the same file system tree at the same
833 // time. Check to see if it exists and make sure it is a directory.
834 int saved_errno = errno;
835 if (!DirectoryExists(subpath)) {
836 if (error)
837 *error = File::OSErrorToFileError(saved_errno);
838 errno = saved_errno;
839 return false;
840 }
841 }
842 return true;
843 }
844
845 // ReadFileToStringNonBlockingNonBlocking will read a file to a string. This
846 // method should only be used on files which are known to be non-blocking such
847 // as procfs or sysfs nodes. Additionally, the file is opened as O_NONBLOCK so
848 // it WILL NOT block even if opened on a blocking file. It will return true if
849 // the file read until EOF and it will return false otherwise, errno will remain
850 // set on error conditions. |ret| will be populated with the contents of the
851 // file.
ReadFileToStringNonBlocking(const base::FilePath & file,std::string * ret)852 bool ReadFileToStringNonBlocking(const base::FilePath& file, std::string* ret) {
853 DCHECK(ret);
854 ret->clear();
855
856 const int flags = O_CLOEXEC | O_NONBLOCK | O_RDONLY | O_NOCTTY;
857 base::ScopedFD fd(HANDLE_EINTR(open(file.MaybeAsASCII().c_str(), flags)));
858 if (!fd.is_valid()) {
859 return false;
860 }
861
862 ssize_t bytes_read = 0;
863 do {
864 char buf[4096];
865 bytes_read = HANDLE_EINTR(read(fd.get(), buf, sizeof(buf)));
866 if (bytes_read < 0)
867 return false;
868 if (bytes_read > 0)
869 ret->append(buf, static_cast<size_t>(bytes_read));
870 } while (bytes_read > 0);
871
872 return true;
873 }
874
NormalizeFilePath(const FilePath & path,FilePath * normalized_path)875 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
876 FilePath real_path_result = MakeAbsoluteFilePath(path);
877 if (real_path_result.empty())
878 return false;
879
880 // To be consistant with windows, fail if |real_path_result| is a
881 // directory.
882 if (DirectoryExists(real_path_result))
883 return false;
884
885 *normalized_path = real_path_result;
886 return true;
887 }
888
889 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
890 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
IsLink(const FilePath & file_path)891 bool IsLink(const FilePath& file_path) {
892 stat_wrapper_t st;
893 // If we can't lstat the file, it's safe to assume that the file won't at
894 // least be a 'followable' link.
895 if (File::Lstat(file_path.value().c_str(), &st) != 0)
896 return false;
897 return S_ISLNK(st.st_mode);
898 }
899
GetFileInfo(const FilePath & file_path,File::Info * results)900 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
901 stat_wrapper_t file_info;
902 #if BUILDFLAG(IS_ANDROID)
903 if (file_path.IsContentUri()) {
904 File file = OpenContentUriForRead(file_path);
905 if (!file.IsValid())
906 return false;
907 return file.GetInfo(results);
908 } else {
909 #endif // BUILDFLAG(IS_ANDROID)
910 if (File::Stat(file_path.value().c_str(), &file_info) != 0)
911 return false;
912 #if BUILDFLAG(IS_ANDROID)
913 }
914 #endif // BUILDFLAG(IS_ANDROID)
915
916 results->FromStat(file_info);
917 return true;
918 }
919
OpenFile(const FilePath & filename,const char * mode)920 FILE* OpenFile(const FilePath& filename, const char* mode) {
921 // 'e' is unconditionally added below, so be sure there is not one already
922 // present before a comma in |mode|.
923 DCHECK(
924 strchr(mode, 'e') == nullptr ||
925 (strchr(mode, ',') != nullptr && strchr(mode, 'e') > strchr(mode, ',')));
926 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
927 FILE* result = nullptr;
928 #if BUILDFLAG(IS_APPLE)
929 // macOS does not provide a mode character to set O_CLOEXEC; see
930 // https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/fopen.3.html.
931 const char* the_mode = mode;
932 #else
933 std::string mode_with_e(AppendModeCharacter(mode, 'e'));
934 const char* the_mode = mode_with_e.c_str();
935 #endif
936 do {
937 result = fopen(filename.value().c_str(), the_mode);
938 } while (!result && errno == EINTR);
939 #if BUILDFLAG(IS_APPLE)
940 // Mark the descriptor as close-on-exec.
941 if (result)
942 SetCloseOnExec(fileno(result));
943 #endif
944 return result;
945 }
946
947 // NaCl doesn't implement system calls to open files directly.
948 #if !BUILDFLAG(IS_NACL)
FileToFILE(File file,const char * mode)949 FILE* FileToFILE(File file, const char* mode) {
950 PlatformFile unowned = file.GetPlatformFile();
951 FILE* stream = fdopen(file.TakePlatformFile(), mode);
952 if (!stream)
953 ScopedFD to_be_closed(unowned);
954 return stream;
955 }
956
FILEToFile(FILE * file_stream)957 File FILEToFile(FILE* file_stream) {
958 if (!file_stream)
959 return File();
960
961 PlatformFile fd = fileno(file_stream);
962 DCHECK_NE(fd, -1);
963 ScopedPlatformFile other_fd(HANDLE_EINTR(dup(fd)));
964 if (!other_fd.is_valid())
965 return File(File::GetLastFileError());
966 return File(std::move(other_fd));
967 }
968 #endif // !BUILDFLAG(IS_NACL)
969
ReadFile(const FilePath & filename,span<char> buffer)970 std::optional<uint64_t> ReadFile(const FilePath& filename, span<char> buffer) {
971 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
972 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
973 if (fd < 0) {
974 return std::nullopt;
975 }
976
977 // TODO(crbug.com/1333521): Consider supporting reading more than INT_MAX
978 // bytes.
979 size_t bytes_to_read = static_cast<size_t>(checked_cast<int>(buffer.size()));
980
981 ssize_t bytes_read = HANDLE_EINTR(read(fd, buffer.data(), bytes_to_read));
982 if (IGNORE_EINTR(close(fd)) < 0) {
983 return std::nullopt;
984 }
985 if (bytes_read < 0) {
986 return std::nullopt;
987 }
988
989 static_assert(SSIZE_MAX <= UINT64_MAX);
990 return bytes_read;
991 }
992
WriteFile(const FilePath & filename,const char * data,int size)993 int WriteFile(const FilePath& filename, const char* data, int size) {
994 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
995 if (size < 0)
996 return -1;
997 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
998 if (fd < 0)
999 return -1;
1000
1001 int bytes_written =
1002 WriteFileDescriptor(fd, StringPiece(data, static_cast<size_t>(size)))
1003 ? size
1004 : -1;
1005 if (IGNORE_EINTR(close(fd)) < 0)
1006 return -1;
1007 return bytes_written;
1008 }
1009
WriteFileDescriptor(int fd,span<const uint8_t> data)1010 bool WriteFileDescriptor(int fd, span<const uint8_t> data) {
1011 // Allow for partial writes.
1012 ssize_t bytes_written_total = 0;
1013 ssize_t size = checked_cast<ssize_t>(data.size());
1014 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
1015 bytes_written_total += bytes_written_partial) {
1016 bytes_written_partial =
1017 HANDLE_EINTR(write(fd, data.data() + bytes_written_total,
1018 static_cast<size_t>(size - bytes_written_total)));
1019 if (bytes_written_partial < 0)
1020 return false;
1021 }
1022
1023 return true;
1024 }
1025
WriteFileDescriptor(int fd,StringPiece data)1026 bool WriteFileDescriptor(int fd, StringPiece data) {
1027 return WriteFileDescriptor(fd, as_bytes(make_span(data)));
1028 }
1029
AllocateFileRegion(File * file,int64_t offset,size_t size)1030 bool AllocateFileRegion(File* file, int64_t offset, size_t size) {
1031 DCHECK(file);
1032
1033 // Explicitly extend |file| to the maximum size. Zeros will fill the new
1034 // space. It is assumed that the existing file is fully realized as
1035 // otherwise the entire file would have to be read and possibly written.
1036 const int64_t original_file_len = file->GetLength();
1037 if (original_file_len < 0) {
1038 DPLOG(ERROR) << "fstat " << file->GetPlatformFile();
1039 return false;
1040 }
1041
1042 // Increase the actual length of the file, if necessary. This can fail if
1043 // the disk is full and the OS doesn't support sparse files.
1044 const int64_t new_file_len = offset + static_cast<int64_t>(size);
1045 // If the first condition fails, the cast on the previous line was invalid
1046 // (though not UB).
1047 if (!IsValueInRangeForNumericType<int64_t>(size) ||
1048 !IsValueInRangeForNumericType<off_t>(size) ||
1049 !IsValueInRangeForNumericType<off_t>(new_file_len) ||
1050 !file->SetLength(std::max(original_file_len, new_file_len))) {
1051 DPLOG(ERROR) << "ftruncate " << file->GetPlatformFile();
1052 return false;
1053 }
1054
1055 // Realize the extent of the file so that it can't fail (and crash) later
1056 // when trying to write to a memory page that can't be created. This can
1057 // fail if the disk is full and the file is sparse.
1058
1059 // First try the more effective platform-specific way of allocating the disk
1060 // space. It can fail because the filesystem doesn't support it. In that case,
1061 // use the manual method below.
1062
1063 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1064 if (HANDLE_EINTR(fallocate(file->GetPlatformFile(), 0, offset,
1065 static_cast<off_t>(size))) != -1)
1066 return true;
1067 DPLOG(ERROR) << "fallocate";
1068 #elif BUILDFLAG(IS_APPLE)
1069 // MacOS doesn't support fallocate even though their new APFS filesystem
1070 // does support sparse files. It does, however, have the functionality
1071 // available via fcntl.
1072 // See also: https://openradar.appspot.com/32720223
1073 fstore_t params = {F_ALLOCATEALL, F_PEOFPOSMODE, offset,
1074 static_cast<off_t>(size), 0};
1075 if (fcntl(file->GetPlatformFile(), F_PREALLOCATE, ¶ms) != -1)
1076 return true;
1077 DPLOG(ERROR) << "F_PREALLOCATE";
1078 #endif
1079
1080 // Manually realize the extended file by writing bytes to it at intervals.
1081 blksize_t block_size = 512; // Start with something safe.
1082 stat_wrapper_t statbuf;
1083 if (File::Fstat(file->GetPlatformFile(), &statbuf) == 0 &&
1084 statbuf.st_blksize > 0 &&
1085 std::has_single_bit(base::checked_cast<uint64_t>(statbuf.st_blksize))) {
1086 block_size = static_cast<blksize_t>(statbuf.st_blksize);
1087 }
1088
1089 // Write starting at the next block boundary after the old file length.
1090 const int64_t extension_start = checked_cast<int64_t>(base::bits::AlignUp(
1091 static_cast<size_t>(original_file_len), static_cast<size_t>(block_size)));
1092 for (int64_t i = extension_start; i < new_file_len; i += block_size) {
1093 char existing_byte;
1094 if (HANDLE_EINTR(pread(file->GetPlatformFile(), &existing_byte, 1,
1095 static_cast<off_t>(i))) != 1) {
1096 return false; // Can't read? Not viable.
1097 }
1098 if (existing_byte != 0) {
1099 continue; // Block has data so must already exist.
1100 }
1101 if (HANDLE_EINTR(pwrite(file->GetPlatformFile(), &existing_byte, 1,
1102 static_cast<off_t>(i))) != 1) {
1103 return false; // Can't write? Not viable.
1104 }
1105 }
1106
1107 return true;
1108 }
1109
AppendToFile(const FilePath & filename,span<const uint8_t> data)1110 bool AppendToFile(const FilePath& filename, span<const uint8_t> data) {
1111 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1112 bool ret = true;
1113 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
1114 if (fd < 0) {
1115 VPLOG(1) << "Unable to create file " << filename.value();
1116 return false;
1117 }
1118
1119 // This call will either write all of the data or return false.
1120 if (!WriteFileDescriptor(fd, data)) {
1121 VPLOG(1) << "Error while writing to file " << filename.value();
1122 ret = false;
1123 }
1124
1125 if (IGNORE_EINTR(close(fd)) < 0) {
1126 VPLOG(1) << "Error while closing file " << filename.value();
1127 return false;
1128 }
1129
1130 return ret;
1131 }
1132
AppendToFile(const FilePath & filename,StringPiece data)1133 bool AppendToFile(const FilePath& filename, StringPiece data) {
1134 return AppendToFile(filename, as_bytes(make_span(data)));
1135 }
1136
GetCurrentDirectory(FilePath * dir)1137 bool GetCurrentDirectory(FilePath* dir) {
1138 // getcwd can return ENOENT, which implies it checks against the disk.
1139 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1140
1141 char system_buffer[PATH_MAX] = "";
1142 if (!getcwd(system_buffer, sizeof(system_buffer))) {
1143 return false;
1144 }
1145 *dir = FilePath(system_buffer);
1146 return true;
1147 }
1148
SetCurrentDirectory(const FilePath & path)1149 bool SetCurrentDirectory(const FilePath& path) {
1150 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1151 return chdir(path.value().c_str()) == 0;
1152 }
1153
1154 #if BUILDFLAG(IS_MAC)
VerifyPathControlledByUser(const FilePath & base,const FilePath & path,uid_t owner_uid,const std::set<gid_t> & group_gids)1155 bool VerifyPathControlledByUser(const FilePath& base,
1156 const FilePath& path,
1157 uid_t owner_uid,
1158 const std::set<gid_t>& group_gids) {
1159 if (base != path && !base.IsParent(path)) {
1160 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
1161 << base.value() << "\", path = \"" << path.value() << "\"";
1162 return false;
1163 }
1164
1165 std::vector<FilePath::StringType> base_components = base.GetComponents();
1166 std::vector<FilePath::StringType> path_components = path.GetComponents();
1167 std::vector<FilePath::StringType>::const_iterator ib, ip;
1168 for (ib = base_components.begin(), ip = path_components.begin();
1169 ib != base_components.end(); ++ib, ++ip) {
1170 // |base| must be a subpath of |path|, so all components should match.
1171 // If these CHECKs fail, look at the test that base is a parent of
1172 // path at the top of this function.
1173 CHECK(ip != path_components.end(), base::NotFatalUntil::M125);
1174 DCHECK(*ip == *ib);
1175 }
1176
1177 FilePath current_path = base;
1178 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
1179 return false;
1180
1181 for (; ip != path_components.end(); ++ip) {
1182 current_path = current_path.Append(*ip);
1183 if (!VerifySpecificPathControlledByUser(
1184 current_path, owner_uid, group_gids))
1185 return false;
1186 }
1187 return true;
1188 }
1189
VerifyPathControlledByAdmin(const FilePath & path)1190 bool VerifyPathControlledByAdmin(const FilePath& path) {
1191 const unsigned kRootUid = 0;
1192 const FilePath kFileSystemRoot("/");
1193
1194 // The name of the administrator group on mac os.
1195 const char* const kAdminGroupNames[] = {
1196 "admin",
1197 "wheel"
1198 };
1199
1200 // Reading the groups database may touch the file system.
1201 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1202
1203 std::set<gid_t> allowed_group_ids;
1204 for (int i = 0, ie = std::size(kAdminGroupNames); i < ie; ++i) {
1205 struct group *group_record = getgrnam(kAdminGroupNames[i]);
1206 if (!group_record) {
1207 DPLOG(ERROR) << "Could not get the group ID of group \""
1208 << kAdminGroupNames[i] << "\".";
1209 continue;
1210 }
1211
1212 allowed_group_ids.insert(group_record->gr_gid);
1213 }
1214
1215 return VerifyPathControlledByUser(
1216 kFileSystemRoot, path, kRootUid, allowed_group_ids);
1217 }
1218 #endif // BUILDFLAG(IS_MAC)
1219
GetMaximumPathComponentLength(const FilePath & path)1220 int GetMaximumPathComponentLength(const FilePath& path) {
1221 #if BUILDFLAG(IS_FUCHSIA)
1222 // Return a value we do not expect anyone ever to reach, but which is small
1223 // enough to guard against e.g. bugs causing multi-megabyte paths.
1224 return 1024;
1225 #else
1226 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1227 return saturated_cast<int>(pathconf(path.value().c_str(), _PC_NAME_MAX));
1228 #endif
1229 }
1230
1231 #if !BUILDFLAG(IS_ANDROID)
1232 // This is implemented in file_util_android.cc for that platform.
GetShmemTempDir(bool executable,FilePath * path)1233 bool GetShmemTempDir(bool executable, FilePath* path) {
1234 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
1235 bool disable_dev_shm = false;
1236 #if !BUILDFLAG(IS_CHROMEOS)
1237 disable_dev_shm = CommandLine::ForCurrentProcess()->HasSwitch(
1238 switches::kDisableDevShmUsage);
1239 #endif
1240 bool use_dev_shm = true;
1241 if (executable) {
1242 static const bool s_dev_shm_executable =
1243 IsPathExecutable(FilePath("/dev/shm"));
1244 use_dev_shm = s_dev_shm_executable;
1245 }
1246 if (use_dev_shm && !disable_dev_shm) {
1247 *path = FilePath("/dev/shm");
1248 return true;
1249 }
1250 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
1251 return GetTempDir(path);
1252 }
1253 #endif // !BUILDFLAG(IS_ANDROID)
1254
1255 #if !BUILDFLAG(IS_APPLE)
1256 // Mac has its own implementation, this is for all other Posix systems.
CopyFile(const FilePath & from_path,const FilePath & to_path)1257 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
1258 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1259 File infile;
1260 #if BUILDFLAG(IS_ANDROID)
1261 if (from_path.IsContentUri()) {
1262 infile = OpenContentUriForRead(from_path);
1263 } else {
1264 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
1265 }
1266 #else
1267 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
1268 #endif
1269 if (!infile.IsValid())
1270 return false;
1271
1272 File outfile(to_path, File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
1273 if (!outfile.IsValid())
1274 return false;
1275
1276 return CopyFileContents(infile, outfile);
1277 }
1278 #endif // !BUILDFLAG(IS_APPLE)
1279
PreReadFile(const FilePath & file_path,bool is_executable,bool sequential,int64_t max_bytes)1280 bool PreReadFile(const FilePath& file_path,
1281 bool is_executable,
1282 bool sequential,
1283 int64_t max_bytes) {
1284 DCHECK_GE(max_bytes, 0);
1285
1286 // posix_fadvise() is only available in the Android NDK in API 21+. Older
1287 // versions may have the required kernel support, but don't have enough usage
1288 // to justify backporting.
1289 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
1290 (BUILDFLAG(IS_ANDROID) && __ANDROID_API__ >= 21)
1291 File file(file_path, File::FLAG_OPEN | File::FLAG_READ);
1292 if (!file.IsValid())
1293 return false;
1294
1295 if (max_bytes == 0) {
1296 // fadvise() pre-fetches the entire file when given a zero length.
1297 return true;
1298 }
1299
1300 const PlatformFile fd = file.GetPlatformFile();
1301 const ::off_t len = base::saturated_cast<::off_t>(max_bytes);
1302 const int advice = sequential ? POSIX_FADV_SEQUENTIAL : POSIX_FADV_WILLNEED;
1303 return posix_fadvise(fd, /*offset=*/0, len, advice) == 0;
1304 #elif BUILDFLAG(IS_APPLE)
1305 File file(file_path, File::FLAG_OPEN | File::FLAG_READ);
1306 if (!file.IsValid())
1307 return false;
1308
1309 if (max_bytes == 0) {
1310 // fcntl(F_RDADVISE) fails when given a zero length.
1311 return true;
1312 }
1313
1314 const PlatformFile fd = file.GetPlatformFile();
1315 ::radvisory read_advise_data = {
1316 .ra_offset = 0, .ra_count = base::saturated_cast<int>(max_bytes)};
1317 return fcntl(fd, F_RDADVISE, &read_advise_data) != -1;
1318 #else
1319 return PreReadFileSlow(file_path, max_bytes);
1320 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
1321 // (BUILDFLAG(IS_ANDROID) &&
1322 // __ANDROID_API__ >= 21)
1323 }
1324
1325 // -----------------------------------------------------------------------------
1326
1327 namespace internal {
1328
MoveUnsafe(const FilePath & from_path,const FilePath & to_path)1329 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
1330 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1331 // Windows compatibility: if |to_path| exists, |from_path| and |to_path|
1332 // must be the same type, either both files, or both directories.
1333 stat_wrapper_t to_file_info;
1334 if (File::Stat(to_path.value().c_str(), &to_file_info) == 0) {
1335 stat_wrapper_t from_file_info;
1336 if (File::Stat(from_path.value().c_str(), &from_file_info) != 0)
1337 return false;
1338 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
1339 return false;
1340 }
1341
1342 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
1343 return true;
1344
1345 if (!CopyDirectory(from_path, to_path, true))
1346 return false;
1347
1348 DeletePathRecursively(from_path);
1349 return true;
1350 }
1351
1352 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
CopyFileContentsWithSendfile(File & infile,File & outfile,bool & retry_slow)1353 bool CopyFileContentsWithSendfile(File& infile,
1354 File& outfile,
1355 bool& retry_slow) {
1356 DCHECK(infile.IsValid());
1357 stat_wrapper_t in_file_info;
1358 retry_slow = false;
1359
1360 if (base::File::Fstat(infile.GetPlatformFile(), &in_file_info)) {
1361 return false;
1362 }
1363
1364 int64_t file_size = in_file_info.st_size;
1365 if (file_size < 0)
1366 return false;
1367 if (file_size == 0) {
1368 // Non-regular files can return a file size of 0, things such as pipes,
1369 // sockets, etc. Additionally, kernel seq_files(most procfs files) will also
1370 // return 0 while still reporting as a regular file. Unfortunately, in some
1371 // of these situations there are easy ways to detect them, in others there
1372 // are not. No extra syscalls are needed if it's not a regular file.
1373 //
1374 // Because any attempt to detect it would likely require another syscall,
1375 // let's just fall back to a slow copy which will invoke a single read(2) to
1376 // determine if the file has contents or if it's really a zero length file.
1377 retry_slow = true;
1378 return false;
1379 }
1380
1381 size_t copied = 0;
1382 ssize_t res = 0;
1383 do {
1384 // Don't specify an offset and the kernel will begin reading/writing to the
1385 // current file offsets.
1386 res = HANDLE_EINTR(sendfile(
1387 outfile.GetPlatformFile(), infile.GetPlatformFile(), /*offset=*/nullptr,
1388 /*length=*/static_cast<size_t>(file_size) - copied));
1389 if (res <= 0) {
1390 break;
1391 }
1392
1393 copied += static_cast<size_t>(res);
1394 } while (copied < static_cast<size_t>(file_size));
1395
1396 // Fallback on non-fatal error cases. None of these errors can happen after
1397 // data has started copying, a check is included for good measure. As a result
1398 // file sizes and file offsets will not have changed. A slow fallback and
1399 // proceed without issues.
1400 retry_slow = (copied == 0 && res < 0 &&
1401 (errno == EINVAL || errno == ENOSYS || errno == EPERM));
1402
1403 return res >= 0;
1404 }
1405 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
1406 // BUILDFLAG(IS_ANDROID)
1407
1408 } // namespace internal
1409
1410 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
IsPathExecutable(const FilePath & path)1411 BASE_EXPORT bool IsPathExecutable(const FilePath& path) {
1412 bool result = false;
1413 FilePath tmp_file_path;
1414
1415 ScopedFD fd = CreateAndOpenFdForTemporaryFileInDir(path, &tmp_file_path);
1416 if (fd.is_valid()) {
1417 DeleteFile(tmp_file_path);
1418 long sysconf_result = sysconf(_SC_PAGESIZE);
1419 CHECK_GE(sysconf_result, 0);
1420 size_t pagesize = static_cast<size_t>(sysconf_result);
1421 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
1422 void* mapping = mmap(nullptr, pagesize, PROT_READ, MAP_SHARED, fd.get(), 0);
1423 if (mapping != MAP_FAILED) {
1424 if (HANDLE_EINTR(mprotect(mapping, pagesize, PROT_READ | PROT_EXEC)) == 0)
1425 result = true;
1426 munmap(mapping, pagesize);
1427 }
1428 }
1429 return result;
1430 }
1431 #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
1432
1433 } // namespace base
1434