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>
39 #include <sys/mount.h>
41 #include <sys/statvfs.h>
42 #include <sys/sysmacros.h>
43 #include <sys/types.h>
50 #ifndef UMOUNT_NOFOLLOW
51 #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
54 using namespace std::chrono_literals;
55 using android::base::ReadFileToString;
56 using android::base::StringPrintf;
61 security_context_t sBlkidContext = nullptr;
62 security_context_t sBlkidUntrustedContext = nullptr;
63 security_context_t sFsckContext = nullptr;
64 security_context_t sFsckUntrustedContext = nullptr;
66 bool sSleepOnUnmount = true;
68 static const char* kBlkidPath = "/system/bin/blkid";
69 static const char* kKeyPath = "/data/misc/vold";
71 static const char* kProcFilesystems = "/proc/filesystems";
73 // Lock used to protect process-level SELinux changes from racing with each
74 // other between multiple threads.
75 static std::mutex kSecurityLock;
77 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
78 std::lock_guard<std::mutex> lock(kSecurityLock);
79 const char* cpath = path.c_str();
82 char* secontext = nullptr;
84 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
85 setfscreatecon(secontext);
89 mode_t mode = 0660 | S_IFBLK;
90 if (mknod(cpath, mode, dev) < 0) {
91 if (errno != EEXIST) {
92 PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
99 setfscreatecon(nullptr);
106 status_t DestroyDeviceNode(const std::string& path) {
107 const char* cpath = path.c_str();
108 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
115 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
116 std::lock_guard<std::mutex> lock(kSecurityLock);
117 const char* cpath = path.c_str();
119 char* secontext = nullptr;
121 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
122 setfscreatecon(secontext);
126 int res = fs_prepare_dir(cpath, mode, uid, gid);
129 setfscreatecon(nullptr);
140 status_t ForceUnmount(const std::string& path) {
141 const char* cpath = path.c_str();
142 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
145 // Apps might still be handling eject request, so wait before
146 // we start sending signals
147 if (sSleepOnUnmount) sleep(5);
149 KillProcessesWithOpenFiles(path, SIGINT);
150 if (sSleepOnUnmount) sleep(5);
151 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
155 KillProcessesWithOpenFiles(path, SIGTERM);
156 if (sSleepOnUnmount) sleep(5);
157 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
161 KillProcessesWithOpenFiles(path, SIGKILL);
162 if (sSleepOnUnmount) sleep(5);
163 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
170 status_t KillProcessesUsingPath(const std::string& path) {
171 if (KillProcessesWithOpenFiles(path, SIGINT) == 0) {
174 if (sSleepOnUnmount) sleep(5);
176 if (KillProcessesWithOpenFiles(path, SIGTERM) == 0) {
179 if (sSleepOnUnmount) sleep(5);
181 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
184 if (sSleepOnUnmount) sleep(5);
186 // Send SIGKILL a second time to determine if we've
187 // actually killed everyone with open files
188 if (KillProcessesWithOpenFiles(path, SIGKILL) == 0) {
191 PLOG(ERROR) << "Failed to kill processes using " << path;
195 status_t BindMount(const std::string& source, const std::string& target) {
196 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
197 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
203 bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
204 auto qual = key + "=\"";
207 start = raw.find(qual, start);
208 if (start == std::string::npos) return false;
209 if (start == 0 || raw[start - 1] == ' ') {
214 start += qual.length();
216 auto end = raw.find("\"", start);
217 if (end == std::string::npos) return false;
219 *value = raw.substr(start, end - start);
223 static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
224 std::string* fsLabel, bool untrusted) {
229 std::vector<std::string> cmd;
230 cmd.push_back(kBlkidPath);
232 cmd.push_back("/dev/null");
234 cmd.push_back("TYPE");
236 cmd.push_back("UUID");
238 cmd.push_back("LABEL");
241 std::vector<std::string> output;
242 status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
244 LOG(WARNING) << "blkid failed to identify " << path;
248 for (const auto& line : output) {
249 // Extract values from blkid output, if defined
250 FindValue(line, "TYPE", fsType);
251 FindValue(line, "UUID", fsUuid);
252 FindValue(line, "LABEL", fsLabel);
258 status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
259 std::string* fsLabel) {
260 return readMetadata(path, fsType, fsUuid, fsLabel, false);
263 status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
264 std::string* fsLabel) {
265 return readMetadata(path, fsType, fsUuid, fsLabel, true);
268 static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
269 std::vector<const char*> argv;
270 argv.reserve(args.size() + 1);
271 for (const auto& arg : args) {
275 LOG(DEBUG) << " " << arg;
277 argv.emplace_back(arg.data());
279 argv.emplace_back(nullptr);
283 static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
284 android::base::unique_fd ufd) {
285 std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
287 PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
290 if (output) output->clear();
292 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
294 if (output) output->emplace_back(line);
299 status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
300 security_context_t context) {
301 auto argv = ConvertToArgv(args);
303 android::base::unique_fd pipe_read, pipe_write;
304 if (!android::base::Pipe(&pipe_read, &pipe_write)) {
305 PLOG(ERROR) << "Pipe in ForkExecvp";
312 if (setexeccon(context)) {
313 LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
318 if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
319 PLOG(ERROR) << "dup2 in ForkExecvp";
323 execvp(argv[0], const_cast<char**>(argv.data()));
324 PLOG(ERROR) << "exec in ForkExecvp";
328 PLOG(ERROR) << "fork in ForkExecvp";
333 auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
334 if (st != 0) return st;
337 if (waitpid(pid, &status, 0) == -1) {
338 PLOG(ERROR) << "waitpid in ForkExecvp";
341 if (!WIFEXITED(status)) {
342 LOG(ERROR) << "Process did not exit normally, status: " << status;
345 if (WEXITSTATUS(status)) {
346 LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
347 return WEXITSTATUS(status);
352 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
353 auto argv = ConvertToArgv(args);
358 close(STDOUT_FILENO);
359 close(STDERR_FILENO);
361 execvp(argv[0], const_cast<char**>(argv.data()));
362 PLOG(ERROR) << "exec in ForkExecvpAsync";
366 PLOG(ERROR) << "fork in ForkExecvpAsync";
372 status_t ReadRandomBytes(size_t bytes, std::string& out) {
374 return ReadRandomBytes(bytes, &out[0]);
377 status_t ReadRandomBytes(size_t bytes, char* buf) {
378 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
384 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
397 status_t GenerateRandomUuid(std::string& out) {
398 status_t res = ReadRandomBytes(16, out);
400 out[6] &= 0x0f; /* clear version */
401 out[6] |= 0x40; /* set to version 4 */
402 out[8] &= 0x3f; /* clear variant */
403 out[8] |= 0x80; /* set to IETF variant */
408 status_t HexToStr(const std::string& hex, std::string& str) {
412 for (size_t i = 0; i < hex.size(); i++) {
416 case ' ': case '-': case ':': continue;
417 case 'f': case 'F': val = 15; break;
418 case 'e': case 'E': val = 14; break;
419 case 'd': case 'D': val = 13; break;
420 case 'c': case 'C': val = 12; break;
421 case 'b': case 'B': val = 11; break;
422 case 'a': case 'A': val = 10; break;
423 case '9': val = 9; break;
424 case '8': val = 8; break;
425 case '7': val = 7; break;
426 case '6': val = 6; break;
427 case '5': val = 5; break;
428 case '4': val = 4; break;
429 case '3': val = 3; break;
430 case '2': val = 2; break;
431 case '1': val = 1; break;
432 case '0': val = 0; break;
433 default: return -EINVAL;
446 return even ? OK : -EINVAL;
449 static const char* kLookup = "0123456789abcdef";
451 status_t StrToHex(const std::string& str, std::string& hex) {
453 for (size_t i = 0; i < str.size(); i++) {
454 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
455 hex.push_back(kLookup[str[i] & 0x0F]);
460 status_t StrToHex(const KeyBuffer& str, KeyBuffer& hex) {
462 for (size_t i = 0; i < str.size(); i++) {
463 hex.push_back(kLookup[(str.data()[i] & 0xF0) >> 4]);
464 hex.push_back(kLookup[str.data()[i] & 0x0F]);
469 status_t NormalizeHex(const std::string& in, std::string& out) {
471 if (HexToStr(in, tmp)) {
474 return StrToHex(tmp, out);
477 status_t GetBlockDevSize(int fd, uint64_t* size) {
478 if (ioctl(fd, BLKGETSIZE64, size)) {
485 status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
486 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
493 res = GetBlockDevSize(fd, size);
500 status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
502 status_t res = GetBlockDevSize(path, &size);
508 *nr_sec = size / 512;
513 uint64_t GetFreeBytes(const std::string& path) {
515 if (statvfs(path.c_str(), &sb) == 0) {
516 return (uint64_t)sb.f_bavail * sb.f_frsize;
522 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
523 // eventually be migrated into system/
524 static int64_t stat_size(struct stat* s) {
525 int64_t blksize = s->st_blksize;
526 // count actual blocks used instead of nominal file size
527 int64_t size = s->st_blocks * 512;
530 /* round up to filesystem block size */
531 size = (size + blksize - 1) & (~(blksize - 1));
537 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
538 // eventually be migrated into system/
539 int64_t calculate_dir_size(int dfd) {
551 while ((de = readdir(d))) {
552 const char* name = de->d_name;
553 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
554 size += stat_size(&s);
556 if (de->d_type == DT_DIR) {
559 /* always skip "." and ".." */
560 if (name[0] == '.') {
561 if (name[1] == 0) continue;
562 if ((name[1] == '.') && (name[2] == 0)) continue;
565 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
567 size += calculate_dir_size(subfd);
575 uint64_t GetTreeBytes(const std::string& path) {
576 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
578 PLOG(WARNING) << "Failed to open " << path;
581 return calculate_dir_size(dirfd);
585 bool IsFilesystemSupported(const std::string& fsType) {
586 std::string supported;
587 if (!ReadFileToString(kProcFilesystems, &supported)) {
588 PLOG(ERROR) << "Failed to read supported filesystems";
591 return supported.find(fsType + "\n") != std::string::npos;
594 status_t WipeBlockDevice(const std::string& path) {
596 const char* c_path = path.c_str();
597 uint64_t range[2] = {0, 0};
599 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
601 PLOG(ERROR) << "Failed to open " << path;
605 if (GetBlockDevSize(fd, &range[1]) != OK) {
606 PLOG(ERROR) << "Failed to determine size of " << path;
610 LOG(INFO) << "About to discard " << range[1] << " on " << path;
611 if (ioctl(fd, BLKDISCARD, &range) == 0) {
612 LOG(INFO) << "Discard success on " << path;
615 PLOG(ERROR) << "Discard failure on " << path;
623 static bool isValidFilename(const std::string& name) {
624 if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
631 std::string BuildKeyPath(const std::string& partGuid) {
632 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
635 std::string BuildDataSystemLegacyPath(userid_t userId) {
636 return StringPrintf("%s/system/users/%u", BuildDataPath("").c_str(), userId);
639 std::string BuildDataSystemCePath(userid_t userId) {
640 return StringPrintf("%s/system_ce/%u", BuildDataPath("").c_str(), userId);
643 std::string BuildDataSystemDePath(userid_t userId) {
644 return StringPrintf("%s/system_de/%u", BuildDataPath("").c_str(), userId);
647 std::string BuildDataMiscLegacyPath(userid_t userId) {
648 return StringPrintf("%s/misc/user/%u", BuildDataPath("").c_str(), userId);
651 std::string BuildDataMiscCePath(userid_t userId) {
652 return StringPrintf("%s/misc_ce/%u", BuildDataPath("").c_str(), userId);
655 std::string BuildDataMiscDePath(userid_t userId) {
656 return StringPrintf("%s/misc_de/%u", BuildDataPath("").c_str(), userId);
659 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
660 std::string BuildDataProfilesDePath(userid_t userId) {
661 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath("").c_str(), userId);
664 std::string BuildDataVendorCePath(userid_t userId) {
665 return StringPrintf("%s/vendor_ce/%u", BuildDataPath("").c_str(), userId);
668 std::string BuildDataVendorDePath(userid_t userId) {
669 return StringPrintf("%s/vendor_de/%u", BuildDataPath("").c_str(), userId);
672 std::string BuildDataPath(const std::string& volumeUuid) {
673 // TODO: unify with installd path generation logic
674 if (volumeUuid.empty()) {
677 CHECK(isValidFilename(volumeUuid));
678 return StringPrintf("/mnt/expand/%s", volumeUuid.c_str());
682 std::string BuildDataMediaCePath(const std::string& volumeUuid, userid_t userId) {
683 // TODO: unify with installd path generation logic
684 std::string data(BuildDataPath(volumeUuid));
685 return StringPrintf("%s/media/%u", data.c_str(), userId);
688 std::string BuildDataUserCePath(const std::string& volumeUuid, userid_t userId) {
689 // TODO: unify with installd path generation logic
690 std::string data(BuildDataPath(volumeUuid));
691 if (volumeUuid.empty() && userId == 0) {
692 std::string legacy = StringPrintf("%s/data", data.c_str());
694 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
695 /* /data/data is dir, return /data/data for legacy system */
699 return StringPrintf("%s/user/%u", data.c_str(), userId);
702 std::string BuildDataUserDePath(const std::string& volumeUuid, userid_t userId) {
703 // TODO: unify with installd path generation logic
704 std::string data(BuildDataPath(volumeUuid));
705 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
708 dev_t GetDevice(const std::string& path) {
710 if (stat(path.c_str(), &sb)) {
711 PLOG(WARNING) << "Failed to stat " << path;
718 status_t RestoreconRecursive(const std::string& path) {
719 LOG(DEBUG) << "Starting restorecon of " << path;
721 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
723 android::base::SetProperty(kRestoreconString, "");
724 android::base::SetProperty(kRestoreconString, path);
726 android::base::WaitForProperty(kRestoreconString, path);
728 LOG(DEBUG) << "Finished restorecon of " << path;
732 bool Readlinkat(int dirfd, const std::string& path, std::string* result) {
733 // Shamelessly borrowed from android::base::Readlink()
736 // Most Linux file systems (ext2 and ext4, say) limit symbolic links to
737 // 4095 bytes. Since we'll copy out into the string anyway, it doesn't
738 // waste memory to just start there. We add 1 so that we can recognize
739 // whether it actually fit (rather than being truncated to 4095).
740 std::vector<char> buf(4095 + 1);
742 ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
743 // Unrecoverable error?
744 if (size == -1) return false;
745 // It fit! (If size == buf.size(), it may have been truncated.)
746 if (static_cast<size_t>(size) < buf.size()) {
747 result->assign(&buf[0], size);
750 // Double our buffer and try again.
751 buf.resize(buf.size() * 2);
755 bool IsRunningInEmulator() {
756 return android::base::GetBoolProperty("ro.kernel.qemu", false);
759 static status_t findMountPointsWithPrefix(const std::string& prefix,
760 std::list<std::string>& mountPoints) {
761 // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
762 // when the prefix is /foo/bar
763 std::string prefixWithSlash(prefix);
764 if (prefix.back() != '/') {
765 android::base::StringAppendF(&prefixWithSlash, "/");
768 std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
770 PLOG(ERROR) << "Unable to open /proc/mounts";
774 // Some volumes can be stacked on each other, so force unmount in
775 // reverse order to give us the best chance of success.
776 struct mntent* mnt; // getmntent returns a thread local, so it's safe.
777 while ((mnt = getmntent(mnts.get())) != nullptr) {
778 auto mountPoint = std::string(mnt->mnt_dir) + "/";
779 if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
780 mountPoints.push_front(mountPoint);
786 // Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
787 status_t UnmountTreeWithPrefix(const std::string& prefix) {
788 std::list<std::string> toUnmount;
789 status_t result = findMountPointsWithPrefix(prefix, toUnmount);
793 for (const auto& path : toUnmount) {
794 if (umount2(path.c_str(), MNT_DETACH)) {
795 PLOG(ERROR) << "Failed to unmount " << path;
802 status_t UnmountTree(const std::string& mountPoint) {
803 if (umount2(mountPoint.c_str(), MNT_DETACH)) {
804 PLOG(ERROR) << "Failed to unmount " << mountPoint;
810 // TODO(118708649): fix duplication with init/util.h
811 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
812 android::base::Timer t;
813 while (t.duration() < timeout) {
815 if (stat(filename, &sb) != -1) {
816 LOG(INFO) << "wait for '" << filename << "' took " << t;
819 std::this_thread::sleep_for(10ms);
821 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
825 bool FsyncDirectory(const std::string& dirname) {
826 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
828 PLOG(ERROR) << "Failed to open " << dirname;
831 if (fsync(fd) == -1) {
832 if (errno == EROFS || errno == EINVAL) {
833 PLOG(WARNING) << "Skip fsync " << dirname
834 << " on a file system does not support synchronization";
836 PLOG(ERROR) << "Failed to fsync " << dirname;
844 } // namespace android