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