2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
22 #include <android-base/chrono_utils.h>
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/properties.h>
26 #include <android-base/stringprintf.h>
27 #include <android-base/strings.h>
28 #include <android-base/unique_fd.h>
29 #include <cutils/fs.h>
30 #include <logwrap/logwrap.h>
31 #include <private/android_filesystem_config.h>
32 #include <private/android_projectid_config.h>
37 #include <linux/posix_acl.h>
38 #include <linux/posix_acl_xattr.h>
42 #include <sys/mount.h>
44 #include <sys/statvfs.h>
45 #include <sys/sysmacros.h>
46 #include <sys/types.h>
48 #include <sys/xattr.h>
57 #ifndef UMOUNT_NOFOLLOW
58 #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
61 using namespace std::chrono_literals;
62 using android::base::EndsWith;
63 using android::base::ReadFileToString;
64 using android::base::StartsWith;
65 using android::base::StringPrintf;
66 using android::base::unique_fd;
71 security_context_t sBlkidContext = nullptr;
72 security_context_t sBlkidUntrustedContext = nullptr;
73 security_context_t sFsckContext = nullptr;
74 security_context_t sFsckUntrustedContext = nullptr;
76 bool sSleepOnUnmount = true;
78 static const char* kBlkidPath = "/system/bin/blkid";
79 static const char* kKeyPath = "/data/misc/vold";
81 static const char* kProcDevices = "/proc/devices";
82 static const char* kProcFilesystems = "/proc/filesystems";
84 static const char* kAndroidDir = "/Android/";
85 static const char* kAppDataDir = "/Android/data/";
86 static const char* kAppMediaDir = "/Android/media/";
87 static const char* kAppObbDir = "/Android/obb/";
89 static const char* kMediaProviderCtx = "u:r:mediaprovider:";
90 static const char* kMediaProviderAppCtx = "u:r:mediaprovider_app:";
92 // Lock used to protect process-level SELinux changes from racing with each
93 // other between multiple threads.
94 static std::mutex kSecurityLock;
96 std::string GetFuseMountPathForUser(userid_t user_id, const std::string& relative_upper_path) {
97 return StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str());
100 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
101 std::lock_guard<std::mutex> lock(kSecurityLock);
102 const char* cpath = path.c_str();
105 char* secontext = nullptr;
107 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
108 setfscreatecon(secontext);
112 mode_t mode = 0660 | S_IFBLK;
113 if (mknod(cpath, mode, dev) < 0) {
114 if (errno != EEXIST) {
115 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
122 setfscreatecon(nullptr);
129 status_t DestroyDeviceNode(const std::string& path) {
130 const char* cpath = path.c_str();
131 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
138 // Sets a default ACL on the directory.
139 status_t SetDefaultAcl(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
140 std::vector<gid_t> additionalGids) {
141 if (IsSdcardfsUsed()) {
142 // sdcardfs magically takes care of this
146 size_t num_entries = 3 + (additionalGids.size() > 0 ? additionalGids.size() + 1 : 0);
147 size_t size = sizeof(posix_acl_xattr_header) + num_entries * sizeof(posix_acl_xattr_entry);
148 auto buf = std::make_unique<uint8_t[]>(size);
150 posix_acl_xattr_header* acl_header = reinterpret_cast<posix_acl_xattr_header*>(buf.get());
151 acl_header->a_version = POSIX_ACL_XATTR_VERSION;
153 posix_acl_xattr_entry* entry =
154 reinterpret_cast<posix_acl_xattr_entry*>(buf.get() + sizeof(posix_acl_xattr_header));
158 entry[tag_index].e_tag = ACL_USER_OBJ;
159 // The existing mode_t mask has the ACL in the lower 9 bits:
160 // the lowest 3 for "other", the next 3 the group, the next 3 for the owner
161 // Use the mode_t masks to get these bits out, and shift them to get the
162 // correct value per entity.
164 // Eg if mode_t = 0700, rwx for the owner, then & S_IRWXU >> 6 results in 7
165 entry[tag_index].e_perm = (mode & S_IRWXU) >> 6;
166 entry[tag_index].e_id = uid;
169 entry[tag_index].e_tag = ACL_GROUP_OBJ;
170 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
171 entry[tag_index].e_id = gid;
174 if (additionalGids.size() > 0) {
175 for (gid_t additional_gid : additionalGids) {
176 entry[tag_index].e_tag = ACL_GROUP;
177 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
178 entry[tag_index].e_id = additional_gid;
182 entry[tag_index].e_tag = ACL_MASK;
183 entry[tag_index].e_perm = (mode & S_IRWXG) >> 3;
184 entry[tag_index].e_id = 0;
188 entry[tag_index].e_tag = ACL_OTHER;
189 entry[tag_index].e_perm = mode & S_IRWXO;
190 entry[tag_index].e_id = 0;
192 int ret = setxattr(path.c_str(), XATTR_NAME_POSIX_ACL_DEFAULT, acl_header, size, 0);
195 PLOG(ERROR) << "Failed to set default ACL on " << path;
201 int SetQuotaInherit(const std::string& path) {
204 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
206 PLOG(ERROR) << "Failed to open " << path << " to set project id inheritance.";
210 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
212 PLOG(ERROR) << "Failed to get flags for " << path << " to set project id inheritance.";
216 flags |= FS_PROJINHERIT_FL;
218 ret = ioctl(fd, FS_IOC_SETFLAGS, &flags);
220 PLOG(ERROR) << "Failed to set flags for " << path << " to set project id inheritance.";
227 int SetQuotaProjectId(const std::string& path, long projectId) {
230 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
232 PLOG(ERROR) << "Failed to open " << path << " to set project id.";
236 int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
238 PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
242 fsx.fsx_projid = projectId;
243 ret = ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
245 PLOG(ERROR) << "Failed to set project id on " << path;
251 int PrepareDirWithProjectId(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
253 int ret = fs_prepare_dir(path.c_str(), mode, uid, gid);
259 if (!IsSdcardfsUsed()) {
260 ret = SetQuotaProjectId(path, projectId);
266 static int FixupAppDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid, long projectId) {
267 namespace fs = std::filesystem;
269 // Setup the directory itself correctly
270 int ret = PrepareDirWithProjectId(path, mode, uid, gid, projectId);
275 // Fixup all of its file entries
276 for (const auto& itEntry : fs::directory_iterator(path)) {
277 ret = lchown(itEntry.path().c_str(), uid, gid);
282 ret = chmod(itEntry.path().c_str(), mode);
287 if (!IsSdcardfsUsed()) {
288 ret = SetQuotaProjectId(itEntry.path(), projectId);
298 int PrepareAppDirFromRoot(const std::string& path, const std::string& root, int appUid,
299 bool fixupExisting) {
303 bool sdcardfsSupport = IsSdcardfsUsed();
305 // Make sure the Android/ directories exist and are setup correctly
306 ret = PrepareAndroidDirs(root);
308 LOG(ERROR) << "Failed to prepare Android/ directories.";
312 // Now create the application-specific subdir(s)
313 // path is something like /data/media/0/Android/data/com.foo/files
314 // First, chop off the volume root, eg /data/media/0
315 std::string pathFromRoot = path.substr(root.length());
318 gid_t gid = AID_MEDIA_RW;
319 std::vector<gid_t> additionalGids;
322 // Check that the next part matches one of the allowed Android/ dirs
323 if (StartsWith(pathFromRoot, kAppDataDir)) {
324 appDir = kAppDataDir;
325 if (!sdcardfsSupport) {
326 gid = AID_EXT_DATA_RW;
327 // Also add the app's own UID as a group; since apps belong to a group
328 // that matches their UID, this ensures that they will always have access to
329 // the files created in these dirs, even if they are created by other processes
330 additionalGids.push_back(uid);
332 } else if (StartsWith(pathFromRoot, kAppMediaDir)) {
333 appDir = kAppMediaDir;
334 if (!sdcardfsSupport) {
337 } else if (StartsWith(pathFromRoot, kAppObbDir)) {
339 if (!sdcardfsSupport) {
340 gid = AID_EXT_OBB_RW;
341 // See comments for kAppDataDir above
342 additionalGids.push_back(uid);
345 LOG(ERROR) << "Invalid application directory: " << path;
349 // mode = 770, plus sticky bit on directory to inherit GID when apps
351 mode_t mode = S_IRWXU | S_IRWXG | S_ISGID;
352 // the project ID for application-specific directories is directly
353 // derived from their uid
355 // Chop off the generic application-specific part, eg /Android/data/
356 // this leaves us with something like com.foo/files/
357 std::string leftToCreate = pathFromRoot.substr(appDir.length());
358 if (!EndsWith(leftToCreate, "/")) {
361 std::string pathToCreate = root + appDir;
363 // Derive initial project ID
364 if (appDir == kAppDataDir || appDir == kAppMediaDir) {
365 projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
366 } else if (appDir == kAppObbDir) {
367 projectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
370 while ((pos = leftToCreate.find('/')) != std::string::npos) {
371 std::string component = leftToCreate.substr(0, pos + 1);
372 leftToCreate = leftToCreate.erase(0, pos + 1);
373 pathToCreate = pathToCreate + component;
375 if (appDir == kAppDataDir && depth == 1 && component == "cache/") {
376 // All dirs use the "app" project ID, except for the cache dirs in
377 // Android/data, eg Android/data/com.foo/cache
378 // Note that this "sticks" - eg subdirs of this dir need the same
380 projectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
383 if (fixupExisting && access(pathToCreate.c_str(), F_OK) == 0) {
384 // Fixup all files in this existing directory with the correct UID/GID
386 ret = FixupAppDir(pathToCreate, mode, uid, gid, projectId);
388 ret = PrepareDirWithProjectId(pathToCreate, mode, uid, gid, projectId);
396 // Set the default ACL on the top-level application-specific directories,
397 // to ensure that even if applications run with a umask of 0077,
398 // new directories within these directories will allow the GID
399 // specified here to write; this is necessary for apps like
400 // installers and MTP, that require access here.
402 // See man (5) acl for more details.
403 ret = SetDefaultAcl(pathToCreate, mode, uid, gid, additionalGids);
408 if (!sdcardfsSupport) {
409 // Set project ID inheritance, so that future subdirectories inherit the
411 ret = SetQuotaInherit(pathToCreate);
424 int SetAttrs(const std::string& path, unsigned int attrs) {
426 android::base::unique_fd fd(
427 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
430 PLOG(ERROR) << "Failed to open " << path;
434 if (ioctl(fd, FS_IOC_GETFLAGS, &flags)) {
435 PLOG(ERROR) << "Failed to get flags for " << path;
439 if ((flags & attrs) == attrs) return 0;
441 if (ioctl(fd, FS_IOC_SETFLAGS, &flags)) {
442 PLOG(ERROR) << "Failed to set flags for " << path << "(0x" << std::hex << attrs << ")";
448 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid,
449 unsigned int attrs) {
450 std::lock_guard<std::mutex> lock(kSecurityLock);
451 const char* cpath = path.c_str();
453 char* secontext = nullptr;
455 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
456 setfscreatecon(secontext);
460 int res = fs_prepare_dir(cpath, mode, uid, gid);
463 setfscreatecon(nullptr);
467 if (res) return -errno;
468 if (attrs) res = SetAttrs(path, attrs);
477 status_t ForceUnmount(const std::string& path) {
478 const char* cpath = path.c_str();
479 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
482 // Apps might still be handling eject request, so wait before
483 // we start sending signals
484 if (sSleepOnUnmount) sleep(5);
486 KillProcessesWithOpenFiles(path, SIGINT);
487 if (sSleepOnUnmount) sleep(5);
488 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
492 KillProcessesWithOpenFiles(path, SIGTERM);
493 if (sSleepOnUnmount) sleep(5);
494 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
498 KillProcessesWithOpenFiles(path, SIGKILL);
499 if (sSleepOnUnmount) sleep(5);
500 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
503 PLOG(INFO) << "ForceUnmount failed";
507 status_t KillProcessesWithTmpfsMountPrefix(const std::string& path) {
508 if (KillProcessesWithTmpfsMounts(path, SIGINT) == 0) {
511 if (sSleepOnUnmount) sleep(5);
513 if (KillProcessesWithTmpfsMounts(path, SIGTERM) == 0) {
516 if (sSleepOnUnmount) sleep(5);
518 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
521 if (sSleepOnUnmount) sleep(5);
523 // Send SIGKILL a second time to determine if we've
524 // actually killed everyone mount
525 if (KillProcessesWithTmpfsMounts(path, SIGKILL) == 0) {
528 PLOG(ERROR) << "Failed to kill processes using " << path;
532 status_t KillProcessesUsingPath(const std::string& path) {
533 if (KillProcessesWithOpenFiles(path, SIGINT, false /* killFuseDaemon */) == 0) {
536 if (sSleepOnUnmount) sleep(5);
538 if (KillProcessesWithOpenFiles(path, SIGTERM, false /* killFuseDaemon */) == 0) {
541 if (sSleepOnUnmount) sleep(5);
543 if (KillProcessesWithOpenFiles(path, SIGKILL, false /* killFuseDaemon */) == 0) {
546 if (sSleepOnUnmount) sleep(5);
548 // Send SIGKILL a second time to determine if we've
549 // actually killed everyone with open files
550 // This time, we also kill the FUSE daemon if found
551 if (KillProcessesWithOpenFiles(path, SIGKILL, true /* killFuseDaemon */) == 0) {
554 PLOG(ERROR) << "Failed to kill processes using " << path;
558 status_t BindMount(const std::string& source, const std::string& target) {
559 if (UnmountTree(target) < 0) {
562 if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
563 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
569 status_t Symlink(const std::string& target, const std::string& linkpath) {
570 if (Unlink(linkpath) < 0) {
573 if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
574 PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
580 status_t Unlink(const std::string& linkpath) {
581 if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
582 PLOG(ERROR) << "Failed to unlink " << linkpath;
588 status_t CreateDir(const std::string& dir, mode_t mode) {
590 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
591 if (S_ISDIR(sb.st_mode)) {
593 } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
594 PLOG(ERROR) << "Failed to unlink " << dir;
597 } else if (errno != ENOENT) {
598 PLOG(ERROR) << "Failed to stat " << dir;
601 if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
602 PLOG(ERROR) << "Failed to mkdir " << dir;
608 bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
609 auto qual = key + "=\"";
612 start = raw.find(qual, start);
613 if (start == std::string::npos) return false;
614 if (start == 0 || raw[start - 1] == ' ') {
619 start += qual.length();
621 auto end = raw.find("\"", start);
622 if (end == std::string::npos) return false;
624 *value = raw.substr(start, end - start);
628 static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
629 std::string* fsLabel, bool untrusted) {
634 std::vector<std::string> cmd;
635 cmd.push_back(kBlkidPath);
637 cmd.push_back("/dev/null");
639 cmd.push_back("TYPE");
641 cmd.push_back("UUID");
643 cmd.push_back("LABEL");
646 std::vector<std::string> output;
647 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
649 LOG(WARNING) << "blkid failed to identify " << path;
653 for (const auto& line : output) {
654 // Extract values from blkid output, if defined
655 FindValue(line, "TYPE", fsType);
656 FindValue(line, "UUID", fsUuid);
657 FindValue(line, "LABEL", fsLabel);
663 status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
664 std::string* fsLabel) {
665 return readMetadata(path, fsType, fsUuid, fsLabel, false);
668 status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
669 std::string* fsLabel) {
670 return readMetadata(path, fsType, fsUuid, fsLabel, true);
673 static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
674 std::vector<const char*> argv;
675 argv.reserve(args.size() + 1);
676 for (const auto& arg : args) {
680 LOG(DEBUG) << " " << arg;
682 argv.emplace_back(arg.data());
684 argv.emplace_back(nullptr);
688 static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
689 android::base::unique_fd ufd) {
690 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
692 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
695 if (output) output->clear();
697 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
699 if (output) output->emplace_back(line);
704 status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
705 security_context_t context) {
706 auto argv = ConvertToArgv(args);
708 android::base::unique_fd pipe_read, pipe_write;
709 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
710 PLOG(ERROR) << "Pipe in ForkExecvp";
717 if (setexeccon(context)) {
718 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
723 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
724 PLOG(ERROR) << "dup2 in ForkExecvp";
728 execvp(argv[0], const_cast<char**>(argv.data()));
729 PLOG(ERROR) << "exec in ForkExecvp";
733 PLOG(ERROR) << "fork in ForkExecvp";
738 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
739 if (st != 0) return st;
742 if (waitpid(pid, &status, 0) == -1) {
743 PLOG(ERROR) << "waitpid in ForkExecvp";
746 if (!WIFEXITED(status)) {
747 LOG(ERROR) << "Process did not exit normally, status: " << status;
750 if (WEXITSTATUS(status)) {
751 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
752 return WEXITSTATUS(status);
757 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
758 auto argv = ConvertToArgv(args);
763 close(STDOUT_FILENO);
764 close(STDERR_FILENO);
766 execvp(argv[0], const_cast<char**>(argv.data()));
767 PLOG(ERROR) << "exec in ForkExecvpAsync";
771 PLOG(ERROR) << "fork in ForkExecvpAsync";
777 status_t ReadRandomBytes(size_t bytes, std::string& out) {
779 return ReadRandomBytes(bytes, &out[0]);
782 status_t ReadRandomBytes(size_t bytes, char* buf) {
783 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
789 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
802 status_t GenerateRandomUuid(std::string& out) {
803 status_t res = ReadRandomBytes(16, out);
805 out[6] &= 0x0f; /* clear version */
806 out[6] |= 0x40; /* set to version 4 */
807 out[8] &= 0x3f; /* clear variant */
808 out[8] |= 0x80; /* set to IETF variant */
813 status_t HexToStr(const std::string& hex, std::string& str) {
817 for (size_t i = 0; i < hex.size(); i++) {
821 case ' ': case '-': case ':': continue;
822 case 'f': case 'F': val = 15; break;
823 case 'e': case 'E': val = 14; break;
824 case 'd': case 'D': val = 13; break;
825 case 'c': case 'C': val = 12; break;
826 case 'b': case 'B': val = 11; break;
827 case 'a': case 'A': val = 10; break;
828 case '9': val = 9; break;
829 case '8': val = 8; break;
830 case '7': val = 7; break;
831 case '6': val = 6; break;
832 case '5': val = 5; break;
833 case '4': val = 4; break;
834 case '3': val = 3; break;
835 case '2': val = 2; break;
836 case '1': val = 1; break;
837 case '0': val = 0; break;
838 default: return -EINVAL;
851 return even ? OK : -EINVAL;
854 static const char* kLookup = "0123456789abcdef";
856 status_t StrToHex(const std::string& str, std::string& hex) {
858 for (size_t i = 0; i < str.size(); i++) {
859 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
860 hex.push_back(kLookup[str[i] & 0x0F]);
865 status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
867 for (size_t i = 0; i < str.size(); i++) {
868 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
869 hex.push_back(kLookup[str.data()[i] & 0x0F]);
874 status_t NormalizeHex(const std::string& in, std::string& out) {
876 if (HexToStr(in, tmp)) {
879 return StrToHex(tmp, out);
882 status_t GetBlockDevSize(int fd, uint64_t* size) {
883 if (ioctl(fd, BLKGETSIZE64, size)) {
890 status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
891 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
898 res = GetBlockDevSize(fd, size);
905 status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
907 status_t res = GetBlockDevSize(path, &size);
913 *nr_sec = size / 512;
918 uint64_t GetFreeBytes(const std::string& path) {
920 if (statvfs(path.c_str(), &sb) == 0) {
921 return (uint64_t)sb.f_bavail * sb.f_frsize;
927 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
928 // eventually be migrated into system/
929 static int64_t stat_size(struct stat* s) {
930 int64_t blksize = s->st_blksize;
931 // count actual blocks used instead of nominal file size
932 int64_t size = s->st_blocks * 512;
935 /* round up to filesystem block size */
936 size = (size + blksize - 1) & (~(blksize - 1));
942 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
943 // eventually be migrated into system/
944 int64_t calculate_dir_size(int dfd) {
956 while ((de = readdir(d))) {
957 const char* name = de->d_name;
958 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
959 size += stat_size(&s);
961 if (de->d_type == DT_DIR) {
964 /* always skip "." and ".." */
965 if (IsDotOrDotDot(*de)) continue;
967 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
969 size += calculate_dir_size(subfd);
977 uint64_t GetTreeBytes(const std::string& path) {
978 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
980 PLOG(WARNING) << "Failed to open " << path;
983 return calculate_dir_size(dirfd);
987 // TODO: Use a better way to determine if it's media provider app.
988 bool IsFuseDaemon(const pid_t pid) {
989 auto path = StringPrintf("/proc/%d/mounts", pid);
991 if (lgetfilecon(path.c_str(), &tmp) < 0) {
994 bool result = android::base::StartsWith(tmp, kMediaProviderAppCtx)
995 || android::base::StartsWith(tmp, kMediaProviderCtx);
1000 bool IsFilesystemSupported(const std::string& fsType) {
1001 std::string supported;
1002 if (!ReadFileToString(kProcFilesystems, &supported)) {
1003 PLOG(ERROR) << "Failed to read supported filesystems";
1007 /* fuse filesystems */
1008 supported.append("fuse\tntfs\n");
1010 return supported.find(fsType + "\n") != std::string::npos;
1013 bool IsSdcardfsUsed() {
1014 return IsFilesystemSupported("sdcardfs") &&
1015 base::GetBoolProperty(kExternalStorageSdcardfs, true);
1018 status_t WipeBlockDevice(const std::string& path) {
1020 const char* c_path = path.c_str();
1021 uint64_t range[2] = {0, 0};
1023 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
1025 PLOG(ERROR) << "Failed to open " << path;
1029 if (GetBlockDevSize(fd, &range[1]) != OK) {
1030 PLOG(ERROR) << "Failed to determine size of " << path;
1034 LOG(INFO) << "About to discard " << range[1] << " on " << path;
1035 if (ioctl(fd, BLKDISCARD, &range) == 0) {
1036 LOG(INFO) << "Discard success on " << path;
1039 PLOG(ERROR) << "Discard failure on " << path;
1047 static bool isValidFilename(const std::string& name) {
1048 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
1055 std::string BuildKeyPath(const std::string& partGuid) {
1056 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
1059 std::string BuildDataSystemLegacyPath(userid_t userId) {
1060 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
1063 std::string BuildDataSystemCePath(userid_t userId) {
1064 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
1067 std::string BuildDataSystemDePath(userid_t userId) {
1068 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
1071 std::string BuildDataMiscLegacyPath(userid_t userId) {
1072 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
1075 std::string BuildDataMiscCePath(userid_t userId) {
1076 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
1079 std::string BuildDataMiscDePath(userid_t userId) {
1080 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
1083 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
1084 std::string BuildDataProfilesDePath(userid_t userId) {
1085 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
1088 std::string BuildDataVendorCePath(userid_t userId) {
1089 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
1092 std::string BuildDataVendorDePath(userid_t userId) {
1093 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
1096 std::string BuildDataPath(const std::string& volumeUuid) {
1097 // TODO: unify with installd path generation logic
1098 if (volumeUuid.empty()) {
1101 CHECK(isValidFilename(volumeUuid));
1102 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
1106 std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
1107 // TODO: unify with installd path generation logic
1108 std::string data(BuildDataPath(volumeUuid));
1109 return StringPrintf("%s/media/%u", data.c_str(), userId);
1112 std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
1113 // TODO: unify with installd path generation logic
1114 std::string data(BuildDataPath(volumeUuid));
1115 if (volumeUuid.empty() && userId == 0) {
1116 std::string legacy = StringPrintf("%s/data", data.c_str());
1118 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
1119 /* /data/data is dir, return /data/data for legacy system */
1123 return StringPrintf("%s/user/%u", data.c_str(), userId);
1126 std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
1127 // TODO: unify with installd path generation logic
1128 std::string data(BuildDataPath(volumeUuid));
1129 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
1132 dev_t GetDevice(const std::string& path) {
1134 if (stat(path.c_str(), &sb)) {
1135 PLOG(WARNING) << "Failed to stat " << path;
1142 // Returns true if |path1| names the same existing file or directory as |path2|.
1143 bool IsSameFile(const std::string& path1, const std::string& path2) {
1144 struct stat stbuf1, stbuf2;
1145 if (stat(path1.c_str(), &stbuf1) != 0 || stat(path2.c_str(), &stbuf2) != 0) return false;
1146 return stbuf1.st_ino == stbuf2.st_ino && stbuf1.st_dev == stbuf2.st_dev;
1149 status_t RestoreconRecursive(const std::string& path) {
1150 LOG(DEBUG) << "Starting restorecon of " << path;
1152 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
1154 android::base::SetProperty(kRestoreconString, "");
1155 android::base::SetProperty(kRestoreconString, path);
1157 android::base::WaitForProperty(kRestoreconString, path);
1159 LOG(DEBUG) << "Finished restorecon of " << path;
1163 bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
1164 // Shamelessly borrowed from android::base::Readlink()
1167 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
1168 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
1169 // waste memory to just start there. We add 1 so that we can recognize
1170 // whether it actually fit (rather than being truncated to 4095).
1171 std::vector<char> buf(4095 + 1);
1173 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
1174 // Unrecoverable error?
1175 if (size == -1) return false;
1176 // It fit! (If size == buf.size(), it may have been truncated.)
1177 if (static_cast<size_t>(size) < buf.size()) {
1178 result->assign(&buf[0], size);
1181 // Double our buffer and try again.
1182 buf.resize(buf.size() * 2);
1186 static unsigned int GetMajorBlockVirtioBlk() {
1187 std::string devices;
1188 if (!ReadFileToString(kProcDevices, &devices)) {
1189 PLOG(ERROR) << "Unable to open /proc/devices";
1193 bool blockSection = false;
1194 for (auto line : android::base::Split(devices, "\n")) {
1195 if (line == "Block devices:") {
1196 blockSection = true;
1197 } else if (line == "Character devices:") {
1198 blockSection = false;
1199 } else if (blockSection) {
1200 auto tokens = android::base::Split(line, " ");
1201 if (tokens.size() == 2 && tokens[1] == "virtblk") {
1202 return std::stoul(tokens[0]);
1210 bool IsVirtioBlkDevice(unsigned int major) {
1211 // Most virtualized platforms expose block devices with the virtio-blk
1212 // block device driver. Unfortunately, this driver does not use a fixed
1213 // major number, but relies on the kernel to assign one from a specific
1214 // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
1215 // per Documentation/devices.txt. This is true even for the latest Linux
1216 // kernel (4.4; see init() in drivers/block/virtio_blk.c).
1217 static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
1218 return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
1221 static status_t findMountPointsWithPrefix(const std::string& prefix,
1222 std::list<std::string>& mountPoints) {
1223 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
1224 // when the prefix is /foo/bar
1225 std::string prefixWithSlash(prefix);
1226 if (prefix.back() != '/') {
1227 android::base::StringAppendF(&prefixWithSlash, "/");
1230 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
1232 PLOG(ERROR) << "Unable to open /proc/mounts";
1236 // Some volumes can be stacked on each other, so force unmount in
1237 // reverse order to give us the best chance of success.
1238 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
1239 while ((mnt = getmntent(mnts.get())) != nullptr) {
1240 auto mountPoint = std::string(mnt->mnt_dir) + "/";
1241 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
1242 mountPoints.push_front(mountPoint);
1248 // Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
1249 status_t UnmountTreeWithPrefix(const std::string& prefix) {
1250 std::list<std::string> toUnmount;
1251 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
1255 for (const auto& path : toUnmount) {
1256 if (umount2(path.c_str(), MNT_DETACH)) {
1257 PLOG(ERROR) << "Failed to unmount " << path;
1264 status_t UnmountTree(const std::string& mountPoint) {
1265 if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
1267 PLOG(ERROR) << "Failed to unmount " << mountPoint;
1273 bool IsDotOrDotDot(const struct dirent& ent) {
1274 return strcmp(ent.d_name, ".") == 0 || strcmp(ent.d_name, "..") == 0;
1277 static status_t delete_dir_contents(DIR* dir) {
1278 // Shamelessly borrowed from android::installd
1279 int dfd = dirfd(dir);
1284 status_t result = OK;
1286 while ((de = readdir(dir))) {
1287 const char* name = de->d_name;
1288 if (de->d_type == DT_DIR) {
1289 /* always skip "." and ".." */
1290 if (IsDotOrDotDot(*de)) continue;
1292 android::base::unique_fd subfd(
1293 openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
1294 if (subfd.get() == -1) {
1295 PLOG(ERROR) << "Couldn't openat " << name;
1299 std::unique_ptr<DIR, decltype(&closedir)> subdirp(
1300 android::base::Fdopendir(std::move(subfd)), closedir);
1302 PLOG(ERROR) << "Couldn't fdopendir " << name;
1306 result = delete_dir_contents(subdirp.get());
1307 if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
1308 PLOG(ERROR) << "Couldn't unlinkat " << name;
1312 if (unlinkat(dfd, name, 0) < 0) {
1313 PLOG(ERROR) << "Couldn't unlinkat " << name;
1321 status_t DeleteDirContentsAndDir(const std::string& pathname) {
1322 status_t res = DeleteDirContents(pathname);
1326 if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
1327 PLOG(ERROR) << "rmdir failed on " << pathname;
1330 LOG(VERBOSE) << "Success: rmdir on " << pathname;
1334 status_t DeleteDirContents(const std::string& pathname) {
1335 // Shamelessly borrowed from android::installd
1336 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
1338 if (errno == ENOENT) {
1341 PLOG(ERROR) << "Failed to opendir " << pathname;
1344 return delete_dir_contents(dirp.get());
1347 // TODO(118708649): fix duplication with init/util.h
1348 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
1349 android::base::Timer t;
1350 while (t.duration() < timeout) {
1352 if (stat(filename, &sb) != -1) {
1353 LOG(INFO) << "wait for '" << filename << "' took " << t;
1356 std::this_thread::sleep_for(10ms);
1358 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
1362 bool pathExists(const std::string& path) {
1363 return access(path.c_str(), F_OK) == 0;
1366 bool FsyncDirectory(const std::string& dirname) {
1367 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
1369 PLOG(ERROR) << "Failed to open " << dirname;
1372 if (fsync(fd) == -1) {
1373 if (errno == EROFS || errno == EINVAL) {
1374 PLOG(WARNING) << "Skip fsync " << dirname
1375 << " on a file system does not support synchronization";
1377 PLOG(ERROR) << "Failed to fsync " << dirname;
1384 bool FsyncParentDirectory(const std::string& path) {
1385 return FsyncDirectory(android::base::Dirname(path));
1388 // Creates all parent directories of |path| that don't already exist. Assigns
1389 // the specified |mode| to any new directories, and also fsync()s their parent
1390 // directories so that the new directories get written to disk right away.
1391 bool MkdirsSync(const std::string& path, mode_t mode) {
1392 if (path[0] != '/') {
1393 LOG(ERROR) << "MkdirsSync() needs an absolute path, but got " << path;
1396 std::vector<std::string> components = android::base::Split(android::base::Dirname(path), "/");
1398 std::string current_dir = "/";
1399 for (const std::string& component : components) {
1400 if (component.empty()) continue;
1402 std::string parent_dir = current_dir;
1403 if (current_dir != "/") current_dir += "/";
1404 current_dir += component;
1406 if (!pathExists(current_dir)) {
1407 if (mkdir(current_dir.c_str(), mode) != 0) {
1408 PLOG(ERROR) << "Failed to create " << current_dir;
1411 if (!FsyncDirectory(parent_dir)) return false;
1412 LOG(DEBUG) << "Created directory " << current_dir;
1418 bool writeStringToFile(const std::string& payload, const std::string& filename) {
1419 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1420 open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
1422 PLOG(ERROR) << "Failed to open " << filename;
1425 if (!android::base::WriteStringToFd(payload, fd)) {
1426 PLOG(ERROR) << "Failed to write to " << filename;
1427 unlink(filename.c_str());
1430 // fsync as close won't guarantee flush data
1431 // see close(2), fsync(2) and b/68901441
1432 if (fsync(fd) == -1) {
1433 if (errno == EROFS || errno == EINVAL) {
1434 PLOG(WARNING) << "Skip fsync " << filename
1435 << " on a file system does not support synchronization";
1437 PLOG(ERROR) << "Failed to fsync " << filename;
1438 unlink(filename.c_str());
1445 status_t AbortFuseConnections() {
1446 namespace fs = std::filesystem;
1448 for (const auto& itEntry : fs::directory_iterator("/sys/fs/fuse/connections")) {
1449 std::string abortPath = itEntry.path().string() + "/abort";
1450 LOG(DEBUG) << "Aborting fuse connection entry " << abortPath;
1451 bool ret = writeStringToFile("1", abortPath);
1453 LOG(WARNING) << "Failed to write to " << abortPath;
1460 status_t EnsureDirExists(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
1461 if (access(path.c_str(), F_OK) != 0) {
1462 PLOG(WARNING) << "Dir does not exist: " << path;
1463 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
1470 // Gets the sysfs path for parameters of the backing device info (bdi)
1471 static std::string getBdiPathForMount(const std::string& mount) {
1472 // First figure out MAJOR:MINOR of mount. Simplest way is to stat the path.
1474 if (stat(mount.c_str(), &info) != 0) {
1475 PLOG(ERROR) << "Failed to stat " << mount;
1478 unsigned int maj = major(info.st_dev);
1479 unsigned int min = minor(info.st_dev);
1481 return StringPrintf("/sys/class/bdi/%u:%u", maj, min);
1484 // Configures max_ratio for the FUSE filesystem.
1485 void ConfigureMaxDirtyRatioForFuse(const std::string& fuse_mount, unsigned int max_ratio) {
1486 LOG(INFO) << "Configuring max_ratio of " << fuse_mount << " fuse filesystem to " << max_ratio;
1487 if (max_ratio > 100) {
1488 LOG(ERROR) << "Invalid max_ratio: " << max_ratio;
1491 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1492 if (fuseBdiPath == "") {
1495 std::string max_ratio_file = StringPrintf("%s/max_ratio", fuseBdiPath.c_str());
1496 unique_fd fd(TEMP_FAILURE_RETRY(open(max_ratio_file.c_str(), O_WRONLY | O_CLOEXEC)));
1497 if (fd.get() == -1) {
1498 PLOG(ERROR) << "Failed to open " << max_ratio_file;
1501 LOG(INFO) << "Writing " << max_ratio << " to " << max_ratio_file;
1502 if (!WriteStringToFd(std::to_string(max_ratio), fd)) {
1503 PLOG(ERROR) << "Failed to write to " << max_ratio_file;
1507 // Configures read ahead property of the fuse filesystem with the mount point |fuse_mount| by
1508 // writing |read_ahead_kb| to the /sys/class/bdi/MAJOR:MINOR/read_ahead_kb.
1509 void ConfigureReadAheadForFuse(const std::string& fuse_mount, size_t read_ahead_kb) {
1510 LOG(INFO) << "Configuring read_ahead of " << fuse_mount << " fuse filesystem to "
1511 << read_ahead_kb << "kb";
1512 std::string fuseBdiPath = getBdiPathForMount(fuse_mount);
1513 if (fuseBdiPath == "") {
1516 // We found the bdi path for our filesystem, time to configure read ahead!
1517 std::string read_ahead_file = StringPrintf("%s/read_ahead_kb", fuseBdiPath.c_str());
1518 unique_fd fd(TEMP_FAILURE_RETRY(open(read_ahead_file.c_str(), O_WRONLY | O_CLOEXEC)));
1519 if (fd.get() == -1) {
1520 PLOG(ERROR) << "Failed to open " << read_ahead_file;
1523 LOG(INFO) << "Writing " << read_ahead_kb << " to " << read_ahead_file;
1524 if (!WriteStringToFd(std::to_string(read_ahead_kb), fd)) {
1525 PLOG(ERROR) << "Failed to write to " << read_ahead_file;
1529 status_t MountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1530 const std::string& relative_upper_path, android::base::unique_fd* fuse_fd) {
1531 std::string pre_fuse_path(StringPrintf("/mnt/user/%d", user_id));
1532 std::string fuse_path(
1533 StringPrintf("%s/%s", pre_fuse_path.c_str(), relative_upper_path.c_str()));
1535 std::string pre_pass_through_path(StringPrintf("/mnt/pass_through/%d", user_id));
1536 std::string pass_through_path(
1537 StringPrintf("%s/%s", pre_pass_through_path.c_str(), relative_upper_path.c_str()));
1539 // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
1540 // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
1541 auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
1542 if (result != android::OK) {
1543 PLOG(ERROR) << "Failed to prepare directory /mnt/user";
1547 // Shell is neither AID_ROOT nor AID_EVERYBODY. Since it equally needs 'execute' access to
1548 // /mnt/user/0 to 'adb shell ls /sdcard' for instance, we set the uid bit of /mnt/user/0 to
1549 // AID_SHELL. This gives shell access along with apps running as group everybody (user 0 apps)
1550 // These bits should be consistent with what is set in zygote in
1551 // com_android_internal_os_Zygote#MountEmulatedStorage on volume bind mount during app fork
1552 result = PrepareDir(pre_fuse_path, 0710, user_id ? AID_ROOT : AID_SHELL,
1553 multiuser_get_uid(user_id, AID_EVERYBODY));
1554 if (result != android::OK) {
1555 PLOG(ERROR) << "Failed to prepare directory " << pre_fuse_path;
1559 result = PrepareDir(fuse_path, 0700, AID_ROOT, AID_ROOT);
1560 if (result != android::OK) {
1561 PLOG(ERROR) << "Failed to prepare directory " << fuse_path;
1565 result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1566 if (result != android::OK) {
1567 PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
1571 result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
1572 if (result != android::OK) {
1573 PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
1577 if (relative_upper_path == "emulated") {
1578 std::string linkpath(StringPrintf("/mnt/user/%d/self", user_id));
1579 result = PrepareDir(linkpath, 0755, AID_ROOT, AID_ROOT);
1580 if (result != android::OK) {
1581 PLOG(ERROR) << "Failed to prepare directory " << linkpath;
1584 linkpath += "/primary";
1585 Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
1587 std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
1588 result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
1589 if (result != android::OK) {
1590 PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
1593 pass_through_linkpath += "/primary";
1594 Symlink("/storage/emulated/" + std::to_string(user_id), pass_through_linkpath);
1598 fuse_fd->reset(open("/dev/fuse", O_RDWR | O_CLOEXEC));
1599 if (fuse_fd->get() == -1) {
1600 PLOG(ERROR) << "Failed to open /dev/fuse";
1604 // Note: leaving out default_permissions since we don't want kernel to do lower filesystem
1605 // permission checks before routing to FUSE daemon.
1606 const auto opts = StringPrintf(
1610 "user_id=0,group_id=0,",
1613 result = TEMP_FAILURE_RETRY(mount("/dev/fuse", fuse_path.c_str(), "fuse",
1614 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME | MS_LAZYTIME,
1617 PLOG(ERROR) << "Failed to mount " << fuse_path;
1621 if (IsSdcardfsUsed()) {
1622 std::string sdcardfs_path(
1623 StringPrintf("/mnt/runtime/full/%s", relative_upper_path.c_str()));
1625 LOG(INFO) << "Bind mounting " << sdcardfs_path << " to " << pass_through_path;
1626 return BindMount(sdcardfs_path, pass_through_path);
1628 LOG(INFO) << "Bind mounting " << absolute_lower_path << " to " << pass_through_path;
1629 return BindMount(absolute_lower_path, pass_through_path);
1633 status_t UnmountUserFuse(userid_t user_id, const std::string& absolute_lower_path,
1634 const std::string& relative_upper_path) {
1635 std::string fuse_path(StringPrintf("/mnt/user/%d/%s", user_id, relative_upper_path.c_str()));
1636 std::string pass_through_path(
1637 StringPrintf("/mnt/pass_through/%d/%s", user_id, relative_upper_path.c_str()));
1639 LOG(INFO) << "Unmounting fuse path " << fuse_path;
1640 android::status_t result = ForceUnmount(fuse_path);
1641 if (result != android::OK) {
1642 // TODO(b/135341433): MNT_DETACH is needed for fuse because umount2 can fail with EBUSY.
1643 // Figure out why we get EBUSY and remove this special casing if possible.
1644 PLOG(ERROR) << "Failed to unmount. Trying MNT_DETACH " << fuse_path << " ...";
1645 if (umount2(fuse_path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) && errno != EINVAL &&
1647 PLOG(ERROR) << "Failed to unmount with MNT_DETACH " << fuse_path;
1650 result = android::OK;
1652 rmdir(fuse_path.c_str());
1654 LOG(INFO) << "Unmounting pass_through_path " << pass_through_path;
1655 auto status = ForceUnmount(pass_through_path);
1656 if (status != android::OK) {
1657 LOG(ERROR) << "Failed to unmount " << pass_through_path;
1659 rmdir(pass_through_path.c_str());
1664 status_t PrepareAndroidDirs(const std::string& volumeRoot) {
1665 std::string androidDir = volumeRoot + kAndroidDir;
1666 std::string androidDataDir = volumeRoot + kAppDataDir;
1667 std::string androidObbDir = volumeRoot + kAppObbDir;
1668 std::string androidMediaDir = volumeRoot + kAppMediaDir;
1670 bool useSdcardFs = IsSdcardfsUsed();
1672 // mode 0771 + sticky bit for inheriting GIDs
1673 mode_t mode = S_IRWXU | S_IRWXG | S_IXOTH | S_ISGID;
1674 if (fs_prepare_dir(androidDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1675 PLOG(ERROR) << "Failed to create " << androidDir;
1679 gid_t dataGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_DATA_RW;
1680 if (fs_prepare_dir(androidDataDir.c_str(), mode, AID_MEDIA_RW, dataGid) != 0) {
1681 PLOG(ERROR) << "Failed to create " << androidDataDir;
1685 gid_t obbGid = useSdcardFs ? AID_MEDIA_RW : AID_EXT_OBB_RW;
1686 if (fs_prepare_dir(androidObbDir.c_str(), mode, AID_MEDIA_RW, obbGid) != 0) {
1687 PLOG(ERROR) << "Failed to create " << androidObbDir;
1690 // Some other apps, like installers, have write access to the OBB directory
1691 // to pre-download them. To make sure newly created folders in this directory
1692 // have the right permissions, set a default ACL.
1693 SetDefaultAcl(androidObbDir, mode, AID_MEDIA_RW, obbGid, {});
1695 if (fs_prepare_dir(androidMediaDir.c_str(), mode, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
1696 PLOG(ERROR) << "Failed to create " << androidMediaDir;
1703 namespace ab = android::base;
1705 static ab::unique_fd openDirFd(int parentFd, const char* name) {
1706 return ab::unique_fd{::openat(parentFd, name, O_CLOEXEC | O_DIRECTORY | O_PATH | O_NOFOLLOW)};
1709 static ab::unique_fd openAbsolutePathFd(std::string_view path) {
1710 if (path.empty() || path[0] != '/') {
1715 return openDirFd(-1, "/");
1718 // first component is special - it includes the leading slash
1719 auto next = path.find('/', 1);
1720 auto component = std::string(path.substr(0, next));
1721 if (component == "..") {
1725 auto fd = openDirFd(-1, component.c_str());
1729 path.remove_prefix(std::min(next + 1, path.size()));
1730 while (next != path.npos && !path.empty()) {
1731 next = path.find('/');
1732 component.assign(path.substr(0, next));
1733 fd = openDirFd(fd, component.c_str());
1737 path.remove_prefix(std::min(next + 1, path.size()));
1742 std::pair<android::base::unique_fd, std::string> OpenDirInProcfs(std::string_view path) {
1743 auto fd = openAbsolutePathFd(path);
1748 auto linkPath = std::string("/proc/self/fd/") += std::to_string(fd.get());
1749 return {std::move(fd), std::move(linkPath)};
1753 } // namespace android