Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / base / file_util_posix.cc
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/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 <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/errno.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 #if defined(OS_MACOSX)
25 #include <AvailabilityMacros.h>
26 #include "base/mac/foundation_util.h"
27 #elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
28 #include <glib.h>  // for g_get_home_dir()
29 #endif
30
31 #include <fstream>
32
33 #include "base/basictypes.h"
34 #include "base/files/file_enumerator.h"
35 #include "base/files/file_path.h"
36 #include "base/logging.h"
37 #include "base/memory/scoped_ptr.h"
38 #include "base/memory/singleton.h"
39 #include "base/path_service.h"
40 #include "base/posix/eintr_wrapper.h"
41 #include "base/stl_util.h"
42 #include "base/strings/string_util.h"
43 #include "base/strings/stringprintf.h"
44 #include "base/strings/sys_string_conversions.h"
45 #include "base/strings/utf_string_conversions.h"
46 #include "base/sys_info.h"
47 #include "base/threading/thread_restrictions.h"
48 #include "base/time/time.h"
49
50 #if defined(OS_ANDROID)
51 #include "base/android/content_uri_utils.h"
52 #include "base/os_compat_android.h"
53 #endif
54
55 #if !defined(OS_IOS)
56 #include <grp.h>
57 #endif
58
59 namespace base {
60
61 namespace {
62
63 #if defined(OS_BSD) || defined(OS_MACOSX)
64 typedef struct stat stat_wrapper_t;
65 static int CallStat(const char *path, stat_wrapper_t *sb) {
66   ThreadRestrictions::AssertIOAllowed();
67   return stat(path, sb);
68 }
69 static int CallLstat(const char *path, stat_wrapper_t *sb) {
70   ThreadRestrictions::AssertIOAllowed();
71   return lstat(path, sb);
72 }
73 #else
74 typedef struct stat64 stat_wrapper_t;
75 static int CallStat(const char *path, stat_wrapper_t *sb) {
76   ThreadRestrictions::AssertIOAllowed();
77   return stat64(path, sb);
78 }
79 static int CallLstat(const char *path, stat_wrapper_t *sb) {
80   ThreadRestrictions::AssertIOAllowed();
81   return lstat64(path, sb);
82 }
83 #if defined(OS_ANDROID)
84 static int CallFstat(int fd, stat_wrapper_t *sb) {
85   ThreadRestrictions::AssertIOAllowed();
86   return fstat64(fd, sb);
87 }
88 #endif
89 #endif
90
91 // Helper for NormalizeFilePath(), defined below.
92 bool RealPath(const FilePath& path, FilePath* real_path) {
93   ThreadRestrictions::AssertIOAllowed();  // For realpath().
94   FilePath::CharType buf[PATH_MAX];
95   if (!realpath(path.value().c_str(), buf))
96     return false;
97
98   *real_path = FilePath(buf);
99   return true;
100 }
101
102 // Helper for VerifyPathControlledByUser.
103 bool VerifySpecificPathControlledByUser(const FilePath& path,
104                                         uid_t owner_uid,
105                                         const std::set<gid_t>& group_gids) {
106   stat_wrapper_t stat_info;
107   if (CallLstat(path.value().c_str(), &stat_info) != 0) {
108     DPLOG(ERROR) << "Failed to get information on path "
109                  << path.value();
110     return false;
111   }
112
113   if (S_ISLNK(stat_info.st_mode)) {
114     DLOG(ERROR) << "Path " << path.value()
115                << " is a symbolic link.";
116     return false;
117   }
118
119   if (stat_info.st_uid != owner_uid) {
120     DLOG(ERROR) << "Path " << path.value()
121                 << " is owned by the wrong user.";
122     return false;
123   }
124
125   if ((stat_info.st_mode & S_IWGRP) &&
126       !ContainsKey(group_gids, stat_info.st_gid)) {
127     DLOG(ERROR) << "Path " << path.value()
128                 << " is writable by an unprivileged group.";
129     return false;
130   }
131
132   if (stat_info.st_mode & S_IWOTH) {
133     DLOG(ERROR) << "Path " << path.value()
134                 << " is writable by any user.";
135     return false;
136   }
137
138   return true;
139 }
140
141 std::string TempFileName() {
142 #if defined(OS_MACOSX)
143   return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
144 #endif
145
146 #if defined(GOOGLE_CHROME_BUILD)
147   return std::string(".com.google.Chrome.XXXXXX");
148 #else
149   return std::string(".org.chromium.Chromium.XXXXXX");
150 #endif
151 }
152
153 // Creates and opens a temporary file in |directory|, returning the
154 // file descriptor. |path| is set to the temporary file path.
155 // This function does NOT unlink() the file.
156 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
157   ThreadRestrictions::AssertIOAllowed();  // For call to mkstemp().
158   *path = directory.Append(base::TempFileName());
159   const std::string& tmpdir_string = path->value();
160   // this should be OK since mkstemp just replaces characters in place
161   char* buffer = const_cast<char*>(tmpdir_string.c_str());
162
163   return HANDLE_EINTR(mkstemp(buffer));
164 }
165
166 #if defined(OS_LINUX)
167 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
168 // This depends on the mount options used for /dev/shm, which vary among
169 // different Linux distributions and possibly local configuration.  It also
170 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
171 // but its kernel allows mprotect with PROT_EXEC anyway.
172 bool DetermineDevShmExecutable() {
173   bool result = false;
174   FilePath path;
175   int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
176   if (fd >= 0) {
177     file_util::ScopedFD shm_fd_closer(&fd);
178     DeleteFile(path, false);
179     long sysconf_result = sysconf(_SC_PAGESIZE);
180     CHECK_GE(sysconf_result, 0);
181     size_t pagesize = static_cast<size_t>(sysconf_result);
182     CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
183     void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
184     if (mapping != MAP_FAILED) {
185       if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
186         result = true;
187       munmap(mapping, pagesize);
188     }
189   }
190   return result;
191 }
192 #endif  // defined(OS_LINUX)
193
194 }  // namespace
195
196 FilePath MakeAbsoluteFilePath(const FilePath& input) {
197   ThreadRestrictions::AssertIOAllowed();
198   char full_path[PATH_MAX];
199   if (realpath(input.value().c_str(), full_path) == NULL)
200     return FilePath();
201   return FilePath(full_path);
202 }
203
204 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
205 // which works both with and without the recursive flag.  I'm not sure we need
206 // that functionality. If not, remove from file_util_win.cc, otherwise add it
207 // here.
208 bool DeleteFile(const FilePath& path, bool recursive) {
209   ThreadRestrictions::AssertIOAllowed();
210   const char* path_str = path.value().c_str();
211   stat_wrapper_t file_info;
212   int test = CallLstat(path_str, &file_info);
213   if (test != 0) {
214     // The Windows version defines this condition as success.
215     bool ret = (errno == ENOENT || errno == ENOTDIR);
216     return ret;
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   std::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(); success && !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 (success && !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
245 bool ReplaceFile(const FilePath& from_path,
246                  const FilePath& to_path,
247                  File::Error* error) {
248   ThreadRestrictions::AssertIOAllowed();
249   if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
250     return true;
251   if (error)
252     *error = File::OSErrorToFileError(errno);
253   return false;
254 }
255
256 bool CopyDirectory(const FilePath& from_path,
257                    const FilePath& to_path,
258                    bool recursive) {
259   ThreadRestrictions::AssertIOAllowed();
260   // Some old callers of CopyDirectory want it to support wildcards.
261   // After some discussion, we decided to fix those callers.
262   // Break loudly here if anyone tries to do this.
263   DCHECK(to_path.value().find('*') == std::string::npos);
264   DCHECK(from_path.value().find('*') == std::string::npos);
265
266   if (from_path.value().size() >= PATH_MAX) {
267     return false;
268   }
269
270   // This function does not properly handle destinations within the source
271   FilePath real_to_path = to_path;
272   if (PathExists(real_to_path)) {
273     real_to_path = MakeAbsoluteFilePath(real_to_path);
274     if (real_to_path.empty())
275       return false;
276   } else {
277     real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
278     if (real_to_path.empty())
279       return false;
280   }
281   FilePath real_from_path = MakeAbsoluteFilePath(from_path);
282   if (real_from_path.empty())
283     return false;
284   if (real_to_path.value().size() >= real_from_path.value().size() &&
285       real_to_path.value().compare(0, real_from_path.value().size(),
286                                    real_from_path.value()) == 0) {
287     return false;
288   }
289
290   int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
291   if (recursive)
292     traverse_type |= FileEnumerator::DIRECTORIES;
293   FileEnumerator traversal(from_path, recursive, traverse_type);
294
295   // We have to mimic windows behavior here. |to_path| may not exist yet,
296   // start the loop with |to_path|.
297   struct stat from_stat;
298   FilePath current = from_path;
299   if (stat(from_path.value().c_str(), &from_stat) < 0) {
300     DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
301                 << from_path.value() << " errno = " << errno;
302     return false;
303   }
304   struct stat to_path_stat;
305   FilePath from_path_base = from_path;
306   if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
307       S_ISDIR(to_path_stat.st_mode)) {
308     // If the destination already exists and is a directory, then the
309     // top level of source needs to be copied.
310     from_path_base = from_path.DirName();
311   }
312
313   // The Windows version of this function assumes that non-recursive calls
314   // will always have a directory for from_path.
315   // TODO(maruel): This is not necessary anymore.
316   DCHECK(recursive || S_ISDIR(from_stat.st_mode));
317
318   bool success = true;
319   while (success && !current.empty()) {
320     // current is the source path, including from_path, so append
321     // the suffix after from_path to to_path to create the target_path.
322     FilePath target_path(to_path);
323     if (from_path_base != current) {
324       if (!from_path_base.AppendRelativePath(current, &target_path)) {
325         success = false;
326         break;
327       }
328     }
329
330     if (S_ISDIR(from_stat.st_mode)) {
331       if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
332           errno != EEXIST) {
333         DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
334                     << target_path.value() << " errno = " << errno;
335         success = false;
336       }
337     } else if (S_ISREG(from_stat.st_mode)) {
338       if (!CopyFile(current, target_path)) {
339         DLOG(ERROR) << "CopyDirectory() couldn't create file: "
340                     << target_path.value();
341         success = false;
342       }
343     } else {
344       DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
345                     << current.value();
346     }
347
348     current = traversal.Next();
349     if (!current.empty())
350       from_stat = traversal.GetInfo().stat();
351   }
352
353   return success;
354 }
355
356 bool PathExists(const FilePath& path) {
357   ThreadRestrictions::AssertIOAllowed();
358 #if defined(OS_ANDROID)
359   if (path.IsContentUri()) {
360     return ContentUriExists(path);
361   }
362 #endif
363   return access(path.value().c_str(), F_OK) == 0;
364 }
365
366 bool PathIsWritable(const FilePath& path) {
367   ThreadRestrictions::AssertIOAllowed();
368   return access(path.value().c_str(), W_OK) == 0;
369 }
370
371 bool DirectoryExists(const FilePath& path) {
372   ThreadRestrictions::AssertIOAllowed();
373   stat_wrapper_t file_info;
374   if (CallStat(path.value().c_str(), &file_info) == 0)
375     return S_ISDIR(file_info.st_mode);
376   return false;
377 }
378
379 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
380   size_t total_read = 0;
381   while (total_read < bytes) {
382     ssize_t bytes_read =
383         HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
384     if (bytes_read <= 0)
385       break;
386     total_read += bytes_read;
387   }
388   return total_read == bytes;
389 }
390
391 bool CreateSymbolicLink(const FilePath& target_path,
392                         const FilePath& symlink_path) {
393   DCHECK(!symlink_path.empty());
394   DCHECK(!target_path.empty());
395   return ::symlink(target_path.value().c_str(),
396                    symlink_path.value().c_str()) != -1;
397 }
398
399 bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
400   DCHECK(!symlink_path.empty());
401   DCHECK(target_path);
402   char buf[PATH_MAX];
403   ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
404
405   if (count <= 0) {
406     target_path->clear();
407     return false;
408   }
409
410   *target_path = FilePath(FilePath::StringType(buf, count));
411   return true;
412 }
413
414 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
415   ThreadRestrictions::AssertIOAllowed();
416   DCHECK(mode);
417
418   stat_wrapper_t file_info;
419   // Uses stat(), because on symbolic link, lstat() does not return valid
420   // permission bits in st_mode
421   if (CallStat(path.value().c_str(), &file_info) != 0)
422     return false;
423
424   *mode = file_info.st_mode & FILE_PERMISSION_MASK;
425   return true;
426 }
427
428 bool SetPosixFilePermissions(const FilePath& path,
429                              int mode) {
430   ThreadRestrictions::AssertIOAllowed();
431   DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
432
433   // Calls stat() so that we can preserve the higher bits like S_ISGID.
434   stat_wrapper_t stat_buf;
435   if (CallStat(path.value().c_str(), &stat_buf) != 0)
436     return false;
437
438   // Clears the existing permission bits, and adds the new ones.
439   mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
440   updated_mode_bits |= mode & FILE_PERMISSION_MASK;
441
442   if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
443     return false;
444
445   return true;
446 }
447
448 #if !defined(OS_MACOSX)
449 // This is implemented in file_util_mac.mm for Mac.
450 bool GetTempDir(FilePath* path) {
451   const char* tmp = getenv("TMPDIR");
452   if (tmp) {
453     *path = FilePath(tmp);
454   } else {
455 #if defined(OS_ANDROID)
456     return PathService::Get(base::DIR_CACHE, path);
457 #else
458     *path = FilePath("/tmp");
459 #endif
460   }
461   return true;
462 }
463 #endif  // !defined(OS_MACOSX)
464
465 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
466 // This is implemented in file_util_mac.mm and file_util_android.cc for those
467 // platforms.
468 bool GetShmemTempDir(bool executable, FilePath* path) {
469 #if defined(OS_LINUX)
470   bool use_dev_shm = true;
471   if (executable) {
472     static const bool s_dev_shm_executable = DetermineDevShmExecutable();
473     use_dev_shm = s_dev_shm_executable;
474   }
475   if (use_dev_shm) {
476     *path = FilePath("/dev/shm");
477     return true;
478   }
479 #endif
480   return GetTempDir(path);
481 }
482 #endif  // !defined(OS_MACOSX) && !defined(OS_ANDROID)
483
484 #if !defined(OS_MACOSX)
485 FilePath GetHomeDir() {
486 #if defined(OS_CHROMEOS)
487   if (SysInfo::IsRunningOnChromeOS())
488     return FilePath("/home/chronos/user");
489 #endif
490
491   const char* home_dir = getenv("HOME");
492   if (home_dir && home_dir[0])
493     return FilePath(home_dir);
494
495 #if defined(OS_ANDROID)
496   DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
497 #elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
498   // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
499   ThreadRestrictions::AssertIOAllowed();
500
501   home_dir = g_get_home_dir();
502   if (home_dir && home_dir[0])
503     return FilePath(home_dir);
504 #endif
505
506   FilePath rv;
507   if (GetTempDir(&rv))
508     return rv;
509
510   // Last resort.
511   return FilePath("/tmp");
512 }
513 #endif  // !defined(OS_MACOSX)
514
515 bool CreateTemporaryFile(FilePath* path) {
516   ThreadRestrictions::AssertIOAllowed();  // For call to close().
517   FilePath directory;
518   if (!GetTempDir(&directory))
519     return false;
520   int fd = CreateAndOpenFdForTemporaryFile(directory, path);
521   if (fd < 0)
522     return false;
523   close(fd);
524   return true;
525 }
526
527 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
528   FilePath directory;
529   if (!GetShmemTempDir(executable, &directory))
530     return NULL;
531
532   return CreateAndOpenTemporaryFileInDir(directory, path);
533 }
534
535 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
536   int fd = CreateAndOpenFdForTemporaryFile(dir, path);
537   if (fd < 0)
538     return NULL;
539
540   FILE* file = fdopen(fd, "a+");
541   if (!file)
542     close(fd);
543   return file;
544 }
545
546 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
547   ThreadRestrictions::AssertIOAllowed();  // For call to close().
548   int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
549   return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
550 }
551
552 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
553                                         const FilePath::StringType& name_tmpl,
554                                         FilePath* new_dir) {
555   ThreadRestrictions::AssertIOAllowed();  // For call to mkdtemp().
556   DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
557       << "Directory name template must contain \"XXXXXX\".";
558
559   FilePath sub_dir = base_dir.Append(name_tmpl);
560   std::string sub_dir_string = sub_dir.value();
561
562   // this should be OK since mkdtemp just replaces characters in place
563   char* buffer = const_cast<char*>(sub_dir_string.c_str());
564   char* dtemp = mkdtemp(buffer);
565   if (!dtemp) {
566     DPLOG(ERROR) << "mkdtemp";
567     return false;
568   }
569   *new_dir = FilePath(dtemp);
570   return true;
571 }
572
573 bool CreateTemporaryDirInDir(const FilePath& base_dir,
574                              const FilePath::StringType& prefix,
575                              FilePath* new_dir) {
576   FilePath::StringType mkdtemp_template = prefix;
577   mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
578   return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
579 }
580
581 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
582                             FilePath* new_temp_path) {
583   FilePath tmpdir;
584   if (!GetTempDir(&tmpdir))
585     return false;
586
587   return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
588 }
589
590 bool CreateDirectoryAndGetError(const FilePath& full_path,
591                                 File::Error* error) {
592   ThreadRestrictions::AssertIOAllowed();  // For call to mkdir().
593   std::vector<FilePath> subpaths;
594
595   // Collect a list of all parent directories.
596   FilePath last_path = full_path;
597   subpaths.push_back(full_path);
598   for (FilePath path = full_path.DirName();
599        path.value() != last_path.value(); path = path.DirName()) {
600     subpaths.push_back(path);
601     last_path = path;
602   }
603
604   // Iterate through the parents and create the missing ones.
605   for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
606        i != subpaths.rend(); ++i) {
607     if (DirectoryExists(*i))
608       continue;
609     if (mkdir(i->value().c_str(), 0700) == 0)
610       continue;
611     // Mkdir failed, but it might have failed with EEXIST, or some other error
612     // due to the the directory appearing out of thin air. This can occur if
613     // two processes are trying to create the same file system tree at the same
614     // time. Check to see if it exists and make sure it is a directory.
615     int saved_errno = errno;
616     if (!DirectoryExists(*i)) {
617       if (error)
618         *error = File::OSErrorToFileError(saved_errno);
619       return false;
620     }
621   }
622   return true;
623 }
624
625 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
626   FilePath real_path_result;
627   if (!RealPath(path, &real_path_result))
628     return false;
629
630   // To be consistant with windows, fail if |real_path_result| is a
631   // directory.
632   stat_wrapper_t file_info;
633   if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
634       S_ISDIR(file_info.st_mode))
635     return false;
636
637   *normalized_path = real_path_result;
638   return true;
639 }
640
641 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
642 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
643 bool IsLink(const FilePath& file_path) {
644   stat_wrapper_t st;
645   // If we can't lstat the file, it's safe to assume that the file won't at
646   // least be a 'followable' link.
647   if (CallLstat(file_path.value().c_str(), &st) != 0)
648     return false;
649
650   if (S_ISLNK(st.st_mode))
651     return true;
652   else
653     return false;
654 }
655
656 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
657   stat_wrapper_t file_info;
658 #if defined(OS_ANDROID)
659   if (file_path.IsContentUri()) {
660     int fd = OpenContentUriForRead(file_path);
661     if (fd < 0)
662       return false;
663     file_util::ScopedFD scoped_fd(&fd);
664     if (CallFstat(fd, &file_info) != 0)
665       return false;
666   } else {
667 #endif  // defined(OS_ANDROID)
668     if (CallStat(file_path.value().c_str(), &file_info) != 0)
669       return false;
670 #if defined(OS_ANDROID)
671   }
672 #endif  // defined(OS_ANDROID)
673   results->is_directory = S_ISDIR(file_info.st_mode);
674   results->size = file_info.st_size;
675 #if defined(OS_MACOSX)
676   results->last_modified = Time::FromTimeSpec(file_info.st_mtimespec);
677   results->last_accessed = Time::FromTimeSpec(file_info.st_atimespec);
678   results->creation_time = Time::FromTimeSpec(file_info.st_ctimespec);
679 #elif defined(OS_ANDROID)
680   results->last_modified = Time::FromTimeT(file_info.st_mtime);
681   results->last_accessed = Time::FromTimeT(file_info.st_atime);
682   results->creation_time = Time::FromTimeT(file_info.st_ctime);
683 #else
684   results->last_modified = Time::FromTimeSpec(file_info.st_mtim);
685   results->last_accessed = Time::FromTimeSpec(file_info.st_atim);
686   results->creation_time = Time::FromTimeSpec(file_info.st_ctim);
687 #endif
688   return true;
689 }
690
691 FILE* OpenFile(const FilePath& filename, const char* mode) {
692   ThreadRestrictions::AssertIOAllowed();
693   FILE* result = NULL;
694   do {
695     result = fopen(filename.value().c_str(), mode);
696   } while (!result && errno == EINTR);
697   return result;
698 }
699
700 int ReadFile(const FilePath& filename, char* data, int size) {
701   ThreadRestrictions::AssertIOAllowed();
702   int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
703   if (fd < 0)
704     return -1;
705
706   ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
707   if (int ret = IGNORE_EINTR(close(fd)) < 0)
708     return ret;
709   return bytes_read;
710 }
711
712 }  // namespace base
713
714 // -----------------------------------------------------------------------------
715
716 namespace file_util {
717
718 using base::stat_wrapper_t;
719 using base::CallStat;
720 using base::CallLstat;
721 using base::CreateAndOpenFdForTemporaryFile;
722 using base::DirectoryExists;
723 using base::FileEnumerator;
724 using base::FilePath;
725 using base::MakeAbsoluteFilePath;
726 using base::VerifySpecificPathControlledByUser;
727
728 base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
729   const int kMaxAttempts = 20;
730   for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
731     int uniquifier =
732         GetUniquePathNumber(path, base::FilePath::StringType());
733     if (uniquifier < 0)
734       break;
735     base::FilePath test_path = (uniquifier == 0) ? path :
736         path.InsertBeforeExtensionASCII(
737             base::StringPrintf(" (%d)", uniquifier));
738     if (mkdir(test_path.value().c_str(), 0777) == 0)
739       return test_path;
740     else if (errno != EEXIST)
741       break;
742   }
743   return base::FilePath();
744 }
745
746 FILE* OpenFile(const std::string& filename, const char* mode) {
747   return OpenFile(FilePath(filename), mode);
748 }
749
750 int WriteFile(const FilePath& filename, const char* data, int size) {
751   base::ThreadRestrictions::AssertIOAllowed();
752   int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
753   if (fd < 0)
754     return -1;
755
756   int bytes_written = WriteFileDescriptor(fd, data, size);
757   if (int ret = IGNORE_EINTR(close(fd)) < 0)
758     return ret;
759   return bytes_written;
760 }
761
762 int WriteFileDescriptor(const int fd, const char* data, int size) {
763   // Allow for partial writes.
764   ssize_t bytes_written_total = 0;
765   for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
766        bytes_written_total += bytes_written_partial) {
767     bytes_written_partial =
768         HANDLE_EINTR(write(fd, data + bytes_written_total,
769                            size - bytes_written_total));
770     if (bytes_written_partial < 0)
771       return -1;
772   }
773
774   return bytes_written_total;
775 }
776
777 int AppendToFile(const FilePath& filename, const char* data, int size) {
778   base::ThreadRestrictions::AssertIOAllowed();
779   int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
780   if (fd < 0)
781     return -1;
782
783   int bytes_written = WriteFileDescriptor(fd, data, size);
784   if (int ret = IGNORE_EINTR(close(fd)) < 0)
785     return ret;
786   return bytes_written;
787 }
788
789 // Gets the current working directory for the process.
790 bool GetCurrentDirectory(FilePath* dir) {
791   // getcwd can return ENOENT, which implies it checks against the disk.
792   base::ThreadRestrictions::AssertIOAllowed();
793
794   char system_buffer[PATH_MAX] = "";
795   if (!getcwd(system_buffer, sizeof(system_buffer))) {
796     NOTREACHED();
797     return false;
798   }
799   *dir = FilePath(system_buffer);
800   return true;
801 }
802
803 // Sets the current working directory for the process.
804 bool SetCurrentDirectory(const FilePath& path) {
805   base::ThreadRestrictions::AssertIOAllowed();
806   int ret = chdir(path.value().c_str());
807   return !ret;
808 }
809
810 bool VerifyPathControlledByUser(const FilePath& base,
811                                 const FilePath& path,
812                                 uid_t owner_uid,
813                                 const std::set<gid_t>& group_gids) {
814   if (base != path && !base.IsParent(path)) {
815      DLOG(ERROR) << "|base| must be a subdirectory of |path|.  base = \""
816                  << base.value() << "\", path = \"" << path.value() << "\"";
817      return false;
818   }
819
820   std::vector<FilePath::StringType> base_components;
821   std::vector<FilePath::StringType> path_components;
822
823   base.GetComponents(&base_components);
824   path.GetComponents(&path_components);
825
826   std::vector<FilePath::StringType>::const_iterator ib, ip;
827   for (ib = base_components.begin(), ip = path_components.begin();
828        ib != base_components.end(); ++ib, ++ip) {
829     // |base| must be a subpath of |path|, so all components should match.
830     // If these CHECKs fail, look at the test that base is a parent of
831     // path at the top of this function.
832     DCHECK(ip != path_components.end());
833     DCHECK(*ip == *ib);
834   }
835
836   FilePath current_path = base;
837   if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
838     return false;
839
840   for (; ip != path_components.end(); ++ip) {
841     current_path = current_path.Append(*ip);
842     if (!VerifySpecificPathControlledByUser(
843             current_path, owner_uid, group_gids))
844       return false;
845   }
846   return true;
847 }
848
849 #if defined(OS_MACOSX) && !defined(OS_IOS)
850 bool VerifyPathControlledByAdmin(const FilePath& path) {
851   const unsigned kRootUid = 0;
852   const FilePath kFileSystemRoot("/");
853
854   // The name of the administrator group on mac os.
855   const char* const kAdminGroupNames[] = {
856     "admin",
857     "wheel"
858   };
859
860   // Reading the groups database may touch the file system.
861   base::ThreadRestrictions::AssertIOAllowed();
862
863   std::set<gid_t> allowed_group_ids;
864   for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
865     struct group *group_record = getgrnam(kAdminGroupNames[i]);
866     if (!group_record) {
867       DPLOG(ERROR) << "Could not get the group ID of group \""
868                    << kAdminGroupNames[i] << "\".";
869       continue;
870     }
871
872     allowed_group_ids.insert(group_record->gr_gid);
873   }
874
875   return VerifyPathControlledByUser(
876       kFileSystemRoot, path, kRootUid, allowed_group_ids);
877 }
878 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
879
880 int GetMaximumPathComponentLength(const FilePath& path) {
881   base::ThreadRestrictions::AssertIOAllowed();
882   return pathconf(path.value().c_str(), _PC_NAME_MAX);
883 }
884
885 }  // namespace file_util
886
887 namespace base {
888 namespace internal {
889
890 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
891   ThreadRestrictions::AssertIOAllowed();
892   // Windows compatibility: if to_path exists, from_path and to_path
893   // must be the same type, either both files, or both directories.
894   stat_wrapper_t to_file_info;
895   if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
896     stat_wrapper_t from_file_info;
897     if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
898       if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
899         return false;
900     } else {
901       return false;
902     }
903   }
904
905   if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
906     return true;
907
908   if (!CopyDirectory(from_path, to_path, true))
909     return false;
910
911   DeleteFile(from_path, true);
912   return true;
913 }
914
915 #if !defined(OS_MACOSX)
916 // Mac has its own implementation, this is for all other Posix systems.
917 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
918   ThreadRestrictions::AssertIOAllowed();
919   int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
920   if (infile < 0)
921     return false;
922
923   int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
924   if (outfile < 0) {
925     close(infile);
926     return false;
927   }
928
929   const size_t kBufferSize = 32768;
930   std::vector<char> buffer(kBufferSize);
931   bool result = true;
932
933   while (result) {
934     ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
935     if (bytes_read < 0) {
936       result = false;
937       break;
938     }
939     if (bytes_read == 0)
940       break;
941     // Allow for partial writes
942     ssize_t bytes_written_per_read = 0;
943     do {
944       ssize_t bytes_written_partial = HANDLE_EINTR(write(
945           outfile,
946           &buffer[bytes_written_per_read],
947           bytes_read - bytes_written_per_read));
948       if (bytes_written_partial < 0) {
949         result = false;
950         break;
951       }
952       bytes_written_per_read += bytes_written_partial;
953     } while (bytes_written_per_read < bytes_read);
954   }
955
956   if (IGNORE_EINTR(close(infile)) < 0)
957     result = false;
958   if (IGNORE_EINTR(close(outfile)) < 0)
959     result = false;
960
961   return result;
962 }
963 #endif  // !defined(OS_MACOSX)
964
965 }  // namespace internal
966 }  // namespace base