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