• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/files/file_util.h"
6 
7 #include <dirent.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <libgen.h>
11 #include <limits.h>
12 #include <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/stat.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <time.h>
22 #include <unistd.h>
23 
24 #include <iterator>
25 
26 #include "base/command_line.h"
27 #include "base/containers/stack.h"
28 #include "base/environment.h"
29 #include "base/files/file_enumerator.h"
30 #include "base/files/file_path.h"
31 #include "base/files/scoped_file.h"
32 #include "base/logging.h"
33 #include "base/macros.h"
34 #include "base/posix/eintr_wrapper.h"
35 #include "base/stl_util.h"
36 #include "base/strings/string_split.h"
37 #include "base/strings/string_util.h"
38 #include "base/strings/stringprintf.h"
39 #include "base/strings/utf_string_conversions.h"
40 #include "util/build_config.h"
41 
42 #if defined(OS_MACOSX)
43 #include <AvailabilityMacros.h>
44 #endif
45 
46 #if !defined(OS_IOS)
47 #include <grp.h>
48 #endif
49 
50 // We need to do this on AIX due to some inconsistencies in how AIX
51 // handles XOPEN_SOURCE and ALL_SOURCE.
52 #if defined(OS_AIX)
53 extern "C" char* mkdtemp(char* path);
54 #endif
55 
56 namespace base {
57 
58 namespace {
59 
60 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL) || \
61     defined(OS_HAIKU) || defined(OS_ANDROID) && __ANDROID_API__ < 21
CallStat(const char * path,stat_wrapper_t * sb)62 int CallStat(const char* path, stat_wrapper_t* sb) {
63   return stat(path, sb);
64 }
CallLstat(const char * path,stat_wrapper_t * sb)65 int CallLstat(const char* path, stat_wrapper_t* sb) {
66   return lstat(path, sb);
67 }
68 #else
69 int CallStat(const char* path, stat_wrapper_t* sb) {
70   return stat64(path, sb);
71 }
72 int CallLstat(const char* path, stat_wrapper_t* sb) {
73   return lstat64(path, sb);
74 }
75 #endif
76 
77 // Helper for VerifyPathControlledByUser.
VerifySpecificPathControlledByUser(const FilePath & path,uid_t owner_uid,const std::set<gid_t> & group_gids)78 bool VerifySpecificPathControlledByUser(const FilePath& path,
79                                         uid_t owner_uid,
80                                         const std::set<gid_t>& group_gids) {
81   stat_wrapper_t stat_info;
82   if (CallLstat(path.value().c_str(), &stat_info) != 0) {
83     DPLOG(ERROR) << "Failed to get information on path " << path.value();
84     return false;
85   }
86 
87   if (S_ISLNK(stat_info.st_mode)) {
88     DLOG(ERROR) << "Path " << path.value() << " is a symbolic link.";
89     return false;
90   }
91 
92   if (stat_info.st_uid != owner_uid) {
93     DLOG(ERROR) << "Path " << path.value() << " is owned by the wrong user.";
94     return false;
95   }
96 
97   if ((stat_info.st_mode & S_IWGRP) &&
98       !ContainsKey(group_gids, stat_info.st_gid)) {
99     DLOG(ERROR) << "Path " << path.value()
100                 << " is writable by an unprivileged group.";
101     return false;
102   }
103 
104   if (stat_info.st_mode & S_IWOTH) {
105     DLOG(ERROR) << "Path " << path.value() << " is writable by any user.";
106     return false;
107   }
108 
109   return true;
110 }
111 
TempFileName()112 std::string TempFileName() {
113   return std::string(".org.chromium.Chromium.XXXXXX");
114 }
115 
116 #if !defined(OS_MACOSX)
CopyFileContents(File * infile,File * outfile)117 bool CopyFileContents(File* infile, File* outfile) {
118   static constexpr size_t kBufferSize = 32768;
119   std::vector<char> buffer(kBufferSize);
120 
121   for (;;) {
122     ssize_t bytes_read = infile->ReadAtCurrentPos(buffer.data(), buffer.size());
123     if (bytes_read < 0)
124       return false;
125     if (bytes_read == 0)
126       return true;
127     // Allow for partial writes
128     ssize_t bytes_written_per_read = 0;
129     do {
130       ssize_t bytes_written_partial = outfile->WriteAtCurrentPos(
131           &buffer[bytes_written_per_read], bytes_read - bytes_written_per_read);
132       if (bytes_written_partial < 0)
133         return false;
134 
135       bytes_written_per_read += bytes_written_partial;
136     } while (bytes_written_per_read < bytes_read);
137   }
138 
139   NOTREACHED();
140   return false;
141 }
142 
143 // Appends |mode_char| to |mode| before the optional character set encoding; see
144 // https://www.gnu.org/software/libc/manual/html_node/Opening-Streams.html for
145 // details.
AppendModeCharacter(std::string_view mode,char mode_char)146 std::string AppendModeCharacter(std::string_view mode, char mode_char) {
147   std::string result(mode);
148   size_t comma_pos = result.find(',');
149   result.insert(comma_pos == std::string::npos ? result.length() : comma_pos, 1,
150                 mode_char);
151   return result;
152 }
153 #endif
154 
155 }  // namespace
156 
MakeAbsoluteFilePath(const FilePath & input)157 FilePath MakeAbsoluteFilePath(const FilePath& input) {
158   char full_path[PATH_MAX];
159   if (realpath(input.value().c_str(), full_path) == nullptr)
160     return FilePath();
161   return FilePath(full_path);
162 }
163 
164 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
165 // which works both with and without the recursive flag.  I'm not sure we need
166 // that functionality. If not, remove from file_util_win.cc, otherwise add it
167 // here.
DeleteFile(const FilePath & path,bool recursive)168 bool DeleteFile(const FilePath& path, bool recursive) {
169   const char* path_str = path.value().c_str();
170   stat_wrapper_t file_info;
171   if (CallLstat(path_str, &file_info) != 0) {
172     // The Windows version defines this condition as success.
173     return (errno == ENOENT || errno == ENOTDIR);
174   }
175   if (!S_ISDIR(file_info.st_mode))
176     return (unlink(path_str) == 0);
177   if (!recursive)
178     return (rmdir(path_str) == 0);
179 
180   bool success = true;
181   stack<std::string> directories;
182   directories.push(path.value());
183   FileEnumerator traversal(path, true,
184                            FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
185                                FileEnumerator::SHOW_SYM_LINKS);
186   for (FilePath current = traversal.Next(); !current.empty();
187        current = traversal.Next()) {
188     if (traversal.GetInfo().IsDirectory())
189       directories.push(current.value());
190     else
191       success &= (unlink(current.value().c_str()) == 0);
192   }
193 
194   while (!directories.empty()) {
195     FilePath dir = FilePath(directories.top());
196     directories.pop();
197     success &= (rmdir(dir.value().c_str()) == 0);
198   }
199   return success;
200 }
201 
ReplaceFile(const FilePath & from_path,const FilePath & to_path,File::Error * error)202 bool ReplaceFile(const FilePath& from_path,
203                  const FilePath& to_path,
204                  File::Error* error) {
205   if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
206     return true;
207   if (error)
208     *error = File::GetLastFileError();
209   return false;
210 }
211 
CreateLocalNonBlockingPipe(int fds[2])212 bool CreateLocalNonBlockingPipe(int fds[2]) {
213 #if defined(OS_LINUX)
214   return pipe2(fds, O_CLOEXEC | O_NONBLOCK) == 0;
215 #else
216   int raw_fds[2];
217   if (pipe(raw_fds) != 0)
218     return false;
219   ScopedFD fd_out(raw_fds[0]);
220   ScopedFD fd_in(raw_fds[1]);
221   if (!SetCloseOnExec(fd_out.get()))
222     return false;
223   if (!SetCloseOnExec(fd_in.get()))
224     return false;
225   if (!SetNonBlocking(fd_out.get()))
226     return false;
227   if (!SetNonBlocking(fd_in.get()))
228     return false;
229   fds[0] = fd_out.release();
230   fds[1] = fd_in.release();
231   return true;
232 #endif
233 }
234 
SetNonBlocking(int fd)235 bool SetNonBlocking(int fd) {
236   const int flags = fcntl(fd, F_GETFL);
237   if (flags == -1)
238     return false;
239   if (flags & O_NONBLOCK)
240     return true;
241   if (HANDLE_EINTR(fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1)
242     return false;
243   return true;
244 }
245 
SetCloseOnExec(int fd)246 bool SetCloseOnExec(int fd) {
247   const int flags = fcntl(fd, F_GETFD);
248   if (flags == -1)
249     return false;
250   if (flags & FD_CLOEXEC)
251     return true;
252   if (HANDLE_EINTR(fcntl(fd, F_SETFD, flags | FD_CLOEXEC)) == -1)
253     return false;
254   return true;
255 }
256 
PathExists(const FilePath & path)257 bool PathExists(const FilePath& path) {
258   return access(path.value().c_str(), F_OK) == 0;
259 }
260 
PathIsWritable(const FilePath & path)261 bool PathIsWritable(const FilePath& path) {
262   return access(path.value().c_str(), W_OK) == 0;
263 }
264 
DirectoryExists(const FilePath & path)265 bool DirectoryExists(const FilePath& path) {
266   stat_wrapper_t file_info;
267   if (CallStat(path.value().c_str(), &file_info) != 0)
268     return false;
269   return S_ISDIR(file_info.st_mode);
270 }
271 
272 #if !defined(OS_FUCHSIA)
CreateSymbolicLink(const FilePath & target_path,const FilePath & symlink_path)273 bool CreateSymbolicLink(const FilePath& target_path,
274                         const FilePath& symlink_path) {
275   DCHECK(!symlink_path.empty());
276   DCHECK(!target_path.empty());
277   return ::symlink(target_path.value().c_str(), symlink_path.value().c_str()) !=
278          -1;
279 }
280 
ReadSymbolicLink(const FilePath & symlink_path,FilePath * target_path)281 bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
282   DCHECK(!symlink_path.empty());
283   DCHECK(target_path);
284   char buf[PATH_MAX];
285   ssize_t count = ::readlink(symlink_path.value().c_str(), buf, std::size(buf));
286 
287   if (count <= 0) {
288     target_path->clear();
289     return false;
290   }
291 
292   *target_path = FilePath(FilePath::StringType(buf, count));
293   return true;
294 }
295 
GetPosixFilePermissions(const FilePath & path,int * mode)296 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
297   DCHECK(mode);
298 
299   stat_wrapper_t file_info;
300   // Uses stat(), because on symbolic link, lstat() does not return valid
301   // permission bits in st_mode
302   if (CallStat(path.value().c_str(), &file_info) != 0)
303     return false;
304 
305   *mode = file_info.st_mode & FILE_PERMISSION_MASK;
306   return true;
307 }
308 
SetPosixFilePermissions(const FilePath & path,int mode)309 bool SetPosixFilePermissions(const FilePath& path, int mode) {
310   DCHECK_EQ(mode & ~FILE_PERMISSION_MASK, 0);
311 
312   // Calls stat() so that we can preserve the higher bits like S_ISGID.
313   stat_wrapper_t stat_buf;
314   if (CallStat(path.value().c_str(), &stat_buf) != 0)
315     return false;
316 
317   // Clears the existing permission bits, and adds the new ones.
318   mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
319   updated_mode_bits |= mode & FILE_PERMISSION_MASK;
320 
321   if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
322     return false;
323 
324   return true;
325 }
326 
ExecutableExistsInPath(Environment * env,const FilePath::StringType & executable)327 bool ExecutableExistsInPath(Environment* env,
328                             const FilePath::StringType& executable) {
329   std::string path;
330   if (!env->GetVar("PATH", &path)) {
331     LOG(ERROR) << "No $PATH variable. Assuming no " << executable << ".";
332     return false;
333   }
334 
335   for (const std::string_view& cur_path :
336        SplitStringPiece(path, ":", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
337     FilePath file(cur_path);
338     int permissions;
339     if (GetPosixFilePermissions(file.Append(executable), &permissions) &&
340         (permissions & FILE_PERMISSION_EXECUTE_BY_USER))
341       return true;
342   }
343   return false;
344 }
345 
346 #endif  // !OS_FUCHSIA
347 
GetTempDir(FilePath * path)348 bool GetTempDir(FilePath* path) {
349   const char* tmp = getenv("TMPDIR");
350   if (tmp) {
351     *path = FilePath(tmp);
352     return true;
353   }
354 
355   *path = FilePath("/tmp");
356   return true;
357 }
358 
359 #if !defined(OS_MACOSX)  // Mac implementation is in file_util_mac.mm.
GetHomeDir()360 FilePath GetHomeDir() {
361   const char* home_dir = getenv("HOME");
362   if (home_dir && home_dir[0])
363     return FilePath(home_dir);
364 
365   FilePath rv;
366   if (GetTempDir(&rv))
367     return rv;
368 
369   // Last resort.
370   return FilePath("/tmp");
371 }
372 #endif  // !defined(OS_MACOSX)
373 
CreateTemporaryDirInDirImpl(const FilePath & base_dir,const FilePath::StringType & name_tmpl,FilePath * new_dir)374 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
375                                         const FilePath::StringType& name_tmpl,
376                                         FilePath* new_dir) {
377   DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
378       << "Directory name template must contain \"XXXXXX\".";
379 
380   FilePath sub_dir = base_dir.Append(name_tmpl);
381   std::string sub_dir_string = sub_dir.value();
382 
383   // this should be OK since mkdtemp just replaces characters in place
384   char* buffer = const_cast<char*>(sub_dir_string.c_str());
385   char* dtemp = mkdtemp(buffer);
386   if (!dtemp) {
387     DPLOG(ERROR) << "mkdtemp";
388     return false;
389   }
390   *new_dir = FilePath(dtemp);
391   return true;
392 }
393 
CreateTemporaryDirInDir(const FilePath & base_dir,const FilePath::StringType & prefix,FilePath * new_dir)394 bool CreateTemporaryDirInDir(const FilePath& base_dir,
395                              const FilePath::StringType& prefix,
396                              FilePath* new_dir) {
397   FilePath::StringType mkdtemp_template = prefix;
398   mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
399   return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
400 }
401 
CreateNewTempDirectory(const FilePath::StringType & prefix,FilePath * new_temp_path)402 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
403                             FilePath* new_temp_path) {
404   FilePath tmpdir;
405   if (!GetTempDir(&tmpdir))
406     return false;
407 
408   return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
409 }
410 
CreateDirectoryAndGetError(const FilePath & full_path,File::Error * error)411 bool CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error) {
412   std::vector<FilePath> subpaths;
413 
414   // Collect a list of all parent directories.
415   FilePath last_path = full_path;
416   subpaths.push_back(full_path);
417   for (FilePath path = full_path.DirName(); path.value() != last_path.value();
418        path = path.DirName()) {
419     subpaths.push_back(path);
420     last_path = path;
421   }
422 
423   // Iterate through the parents and create the missing ones.
424   for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
425        i != subpaths.rend(); ++i) {
426     if (DirectoryExists(*i))
427       continue;
428     if (mkdir(i->value().c_str(), 0700) == 0)
429       continue;
430     // Mkdir failed, but it might have failed with EEXIST, or some other error
431     // due to the the directory appearing out of thin air. This can occur if
432     // two processes are trying to create the same file system tree at the same
433     // time. Check to see if it exists and make sure it is a directory.
434     int saved_errno = errno;
435     if (!DirectoryExists(*i)) {
436       if (error)
437         *error = File::OSErrorToFileError(saved_errno);
438       return false;
439     }
440   }
441   return true;
442 }
443 
NormalizeFilePath(const FilePath & path,FilePath * normalized_path)444 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
445   FilePath real_path_result = MakeAbsoluteFilePath(path);
446   if (real_path_result.empty())
447     return false;
448 
449   // To be consistant with windows, fail if |real_path_result| is a
450   // directory.
451   if (DirectoryExists(real_path_result))
452     return false;
453 
454   *normalized_path = real_path_result;
455   return true;
456 }
457 
458 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
459 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
IsLink(const FilePath & file_path)460 bool IsLink(const FilePath& file_path) {
461   stat_wrapper_t st;
462   // If we can't lstat the file, it's safe to assume that the file won't at
463   // least be a 'followable' link.
464   if (CallLstat(file_path.value().c_str(), &st) != 0)
465     return false;
466   return S_ISLNK(st.st_mode);
467 }
468 
GetFileInfo(const FilePath & file_path,File::Info * results)469 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
470   stat_wrapper_t file_info;
471   if (CallStat(file_path.value().c_str(), &file_info) != 0)
472     return false;
473 
474   results->FromStat(file_info);
475   return true;
476 }
477 
OpenFile(const FilePath & filename,const char * mode)478 FILE* OpenFile(const FilePath& filename, const char* mode) {
479   // 'e' is unconditionally added below, so be sure there is not one already
480   // present before a comma in |mode|.
481   DCHECK(
482       strchr(mode, 'e') == nullptr ||
483       (strchr(mode, ',') != nullptr && strchr(mode, 'e') > strchr(mode, ',')));
484   FILE* result = nullptr;
485 #if defined(OS_MACOSX)
486   // macOS does not provide a mode character to set O_CLOEXEC; see
487   // https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/fopen.3.html.
488   const char* the_mode = mode;
489 #else
490   std::string mode_with_e(AppendModeCharacter(mode, 'e'));
491   const char* the_mode = mode_with_e.c_str();
492 #endif
493   do {
494     result = fopen(filename.value().c_str(), the_mode);
495   } while (!result && errno == EINTR);
496 #if defined(OS_MACOSX)
497   // Mark the descriptor as close-on-exec.
498   if (result)
499     SetCloseOnExec(fileno(result));
500 #endif
501   return result;
502 }
503 
FileToFILE(File file,const char * mode)504 FILE* FileToFILE(File file, const char* mode) {
505   FILE* stream = fdopen(file.GetPlatformFile(), mode);
506   if (stream)
507     file.TakePlatformFile();
508   return stream;
509 }
510 
ReadFile(const FilePath & filename,char * data,int max_size)511 int ReadFile(const FilePath& filename, char* data, int max_size) {
512   int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
513   if (fd < 0)
514     return -1;
515 
516   ssize_t bytes_read = HANDLE_EINTR(read(fd, data, max_size));
517   if (IGNORE_EINTR(close(fd)) < 0)
518     return -1;
519   return bytes_read;
520 }
521 
WriteFile(const FilePath & filename,const char * data,int size)522 int WriteFile(const FilePath& filename, const char* data, int size) {
523   int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
524   if (fd < 0)
525     return -1;
526 
527   int bytes_written = WriteFileDescriptor(fd, data, size) ? size : -1;
528   if (IGNORE_EINTR(close(fd)) < 0)
529     return -1;
530   return bytes_written;
531 }
532 
WriteFileDescriptor(const int fd,const char * data,int size)533 bool WriteFileDescriptor(const int fd, const char* data, int size) {
534   // Allow for partial writes.
535   ssize_t bytes_written_total = 0;
536   for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
537        bytes_written_total += bytes_written_partial) {
538     bytes_written_partial = HANDLE_EINTR(
539         write(fd, data + bytes_written_total, size - bytes_written_total));
540     if (bytes_written_partial < 0)
541       return false;
542   }
543 
544   return true;
545 }
546 
AppendToFile(const FilePath & filename,const char * data,int size)547 bool AppendToFile(const FilePath& filename, const char* data, int size) {
548   bool ret = true;
549   int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
550   if (fd < 0) {
551     return false;
552   }
553 
554   // This call will either write all of the data or return false.
555   if (!WriteFileDescriptor(fd, data, size)) {
556     ret = false;
557   }
558 
559   if (IGNORE_EINTR(close(fd)) < 0) {
560     return false;
561   }
562 
563   return ret;
564 }
565 
GetCurrentDirectory(FilePath * dir)566 bool GetCurrentDirectory(FilePath* dir) {
567   char system_buffer[PATH_MAX] = "";
568   if (!getcwd(system_buffer, sizeof(system_buffer))) {
569     NOTREACHED();
570     return false;
571   }
572   *dir = FilePath(system_buffer);
573   return true;
574 }
575 
SetCurrentDirectory(const FilePath & path)576 bool SetCurrentDirectory(const FilePath& path) {
577   return chdir(path.value().c_str()) == 0;
578 }
579 
VerifyPathControlledByUser(const FilePath & base,const FilePath & path,uid_t owner_uid,const std::set<gid_t> & group_gids)580 bool VerifyPathControlledByUser(const FilePath& base,
581                                 const FilePath& path,
582                                 uid_t owner_uid,
583                                 const std::set<gid_t>& group_gids) {
584   if (base != path && !base.IsParent(path)) {
585     DLOG(ERROR) << "|base| must be a subdirectory of |path|.  base = \""
586                 << base.value() << "\", path = \"" << path.value() << "\"";
587     return false;
588   }
589 
590   std::vector<FilePath::StringType> base_components;
591   std::vector<FilePath::StringType> path_components;
592 
593   base.GetComponents(&base_components);
594   path.GetComponents(&path_components);
595 
596   std::vector<FilePath::StringType>::const_iterator ib, ip;
597   for (ib = base_components.begin(), ip = path_components.begin();
598        ib != base_components.end(); ++ib, ++ip) {
599     // |base| must be a subpath of |path|, so all components should match.
600     // If these CHECKs fail, look at the test that base is a parent of
601     // path at the top of this function.
602     DCHECK(ip != path_components.end());
603     DCHECK(*ip == *ib);
604   }
605 
606   FilePath current_path = base;
607   if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
608     return false;
609 
610   for (; ip != path_components.end(); ++ip) {
611     current_path = current_path.Append(*ip);
612     if (!VerifySpecificPathControlledByUser(current_path, owner_uid,
613                                             group_gids))
614       return false;
615   }
616   return true;
617 }
618 
619 #if defined(OS_MACOSX) && !defined(OS_IOS)
VerifyPathControlledByAdmin(const FilePath & path)620 bool VerifyPathControlledByAdmin(const FilePath& path) {
621   const unsigned kRootUid = 0;
622   const FilePath kFileSystemRoot("/");
623 
624   // The name of the administrator group on mac os.
625   const char* const kAdminGroupNames[] = {"admin", "wheel"};
626 
627   std::set<gid_t> allowed_group_ids;
628   for (int i = 0, ie = std::size(kAdminGroupNames); i < ie; ++i) {
629     struct group* group_record = getgrnam(kAdminGroupNames[i]);
630     if (!group_record) {
631       DPLOG(ERROR) << "Could not get the group ID of group \""
632                    << kAdminGroupNames[i] << "\".";
633       continue;
634     }
635 
636     allowed_group_ids.insert(group_record->gr_gid);
637   }
638 
639   return VerifyPathControlledByUser(kFileSystemRoot, path, kRootUid,
640                                     allowed_group_ids);
641 }
642 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
643 
GetMaximumPathComponentLength(const FilePath & path)644 int GetMaximumPathComponentLength(const FilePath& path) {
645   return pathconf(path.value().c_str(), _PC_NAME_MAX);
646 }
647 
648 #if !defined(OS_MACOSX)
649 // Mac has its own implementation, this is for all other Posix systems.
CopyFile(const FilePath & from_path,const FilePath & to_path)650 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
651   File infile;
652   infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
653   if (!infile.IsValid())
654     return false;
655 
656   File outfile(to_path, File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
657   if (!outfile.IsValid())
658     return false;
659 
660   return CopyFileContents(&infile, &outfile);
661 }
662 #endif  // !defined(OS_MACOSX)
663 
664 }  // namespace base
665