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