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