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.
21 #include <android-base/file.h>
22 #include <android-base/logging.h>
23 #include <android-base/properties.h>
24 #include <android-base/stringprintf.h>
25 #include <cutils/fs.h>
26 #include <logwrap/logwrap.h>
27 #include <private/android_filesystem_config.h>
34 #include <sys/mount.h>
35 #include <sys/types.h>
37 #include <sys/sysmacros.h>
39 #include <sys/statvfs.h>
41 #ifndef UMOUNT_NOFOLLOW
42 #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
45 using android::base::ReadFileToString;
46 using android::base::StringPrintf;
51 security_context_t sBlkidContext = nullptr;
52 security_context_t sBlkidUntrustedContext = nullptr;
53 security_context_t sFsckContext = nullptr;
54 security_context_t sFsckUntrustedContext = nullptr;
56 static const char* kBlkidPath = "/system/bin/blkid";
57 static const char* kKeyPath = "/data/misc/vold";
59 static const char* kProcFilesystems = "/proc/filesystems";
61 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
62 const char* cpath = path.c_str();
65 char* secontext = nullptr;
67 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
68 setfscreatecon(secontext);
72 mode_t mode = 0660 | S_IFBLK;
73 if (mknod(cpath, mode, dev) < 0) {
74 if (errno != EEXIST) {
75 PLOG(ERROR) << "Failed to create device node for " << major(dev)
76 << ":" << minor(dev) << " at " << path;
82 setfscreatecon(nullptr);
89 status_t DestroyDeviceNode(const std::string& path) {
90 const char* cpath = path.c_str();
91 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
98 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
99 const char* cpath = path.c_str();
101 char* secontext = nullptr;
103 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
104 setfscreatecon(secontext);
108 int res = fs_prepare_dir(cpath, mode, uid, gid);
111 setfscreatecon(nullptr);
122 status_t ForceUnmount(const std::string& path) {
123 const char* cpath = path.c_str();
124 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
127 // Apps might still be handling eject request, so wait before
128 // we start sending signals
131 Process::killProcessesWithOpenFiles(cpath, SIGINT);
133 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
137 Process::killProcessesWithOpenFiles(cpath, SIGTERM);
139 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
143 Process::killProcessesWithOpenFiles(cpath, SIGKILL);
145 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
152 status_t KillProcessesUsingPath(const std::string& path) {
153 const char* cpath = path.c_str();
154 if (Process::killProcessesWithOpenFiles(cpath, SIGINT) == 0) {
159 if (Process::killProcessesWithOpenFiles(cpath, SIGTERM) == 0) {
164 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
169 // Send SIGKILL a second time to determine if we've
170 // actually killed everyone with open files
171 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
174 PLOG(ERROR) << "Failed to kill processes using " << path;
178 status_t BindMount(const std::string& source, const std::string& target) {
179 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
180 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
186 static status_t readMetadata(const std::string& path, std::string& fsType,
187 std::string& fsUuid, std::string& fsLabel, bool untrusted) {
192 std::vector<std::string> cmd;
193 cmd.push_back(kBlkidPath);
195 cmd.push_back("/dev/null");
197 cmd.push_back("TYPE");
199 cmd.push_back("UUID");
201 cmd.push_back("LABEL");
204 std::vector<std::string> output;
205 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
207 LOG(WARNING) << "blkid failed to identify " << path;
212 for (const auto& line : output) {
213 // Extract values from blkid output, if defined
214 const char* cline = line.c_str();
215 const char* start = strstr(cline, "TYPE=");
216 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
220 start = strstr(cline, "UUID=");
221 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
225 start = strstr(cline, "LABEL=");
226 if (start != nullptr && sscanf(start + 6, "\"%127[^\"]\"", value) == 1) {
234 status_t ReadMetadata(const std::string& path, std::string& fsType,
235 std::string& fsUuid, std::string& fsLabel) {
236 return readMetadata(path, fsType, fsUuid, fsLabel, false);
239 status_t ReadMetadataUntrusted(const std::string& path, std::string& fsType,
240 std::string& fsUuid, std::string& fsLabel) {
241 return readMetadata(path, fsType, fsUuid, fsLabel, true);
244 status_t ForkExecvp(const std::vector<std::string>& args) {
245 return ForkExecvp(args, nullptr);
248 status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
249 size_t argc = args.size();
250 char** argv = (char**) calloc(argc, sizeof(char*));
251 for (size_t i = 0; i < argc; i++) {
252 argv[i] = (char*) args[i].c_str();
254 LOG(VERBOSE) << args[i];
256 LOG(VERBOSE) << " " << args[i];
260 if (setexeccon(context)) {
261 LOG(ERROR) << "Failed to setexeccon";
264 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
265 if (setexeccon(nullptr)) {
266 LOG(ERROR) << "Failed to setexeccon";
274 status_t ForkExecvp(const std::vector<std::string>& args,
275 std::vector<std::string>& output) {
276 return ForkExecvp(args, output, nullptr);
279 status_t ForkExecvp(const std::vector<std::string>& args,
280 std::vector<std::string>& output, security_context_t context) {
282 for (size_t i = 0; i < args.size(); i++) {
283 cmd += args[i] + " ";
285 LOG(VERBOSE) << args[i];
287 LOG(VERBOSE) << " " << args[i];
292 if (setexeccon(context)) {
293 LOG(ERROR) << "Failed to setexeccon";
296 FILE* fp = popen(cmd.c_str(), "r");
297 if (setexeccon(nullptr)) {
298 LOG(ERROR) << "Failed to setexeccon";
303 PLOG(ERROR) << "Failed to popen " << cmd;
307 while (fgets(line, sizeof(line), fp) != nullptr) {
308 LOG(VERBOSE) << line;
309 output.push_back(std::string(line));
311 if (pclose(fp) != 0) {
312 PLOG(ERROR) << "Failed to pclose " << cmd;
319 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
320 size_t argc = args.size();
321 char** argv = (char**) calloc(argc + 1, sizeof(char*));
322 for (size_t i = 0; i < argc; i++) {
323 argv[i] = (char*) args[i].c_str();
325 LOG(VERBOSE) << args[i];
327 LOG(VERBOSE) << " " << args[i];
334 close(STDOUT_FILENO);
335 close(STDERR_FILENO);
337 if (execvp(argv[0], argv)) {
338 PLOG(ERROR) << "Failed to exec";
345 PLOG(ERROR) << "Failed to exec";
352 status_t ReadRandomBytes(size_t bytes, std::string& out) {
355 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
362 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], std::min(sizeof(buf), bytes)))) > 0) {
375 status_t HexToStr(const std::string& hex, std::string& str) {
379 for (size_t i = 0; i < hex.size(); i++) {
382 case ' ': case '-': case ':': continue;
383 case 'f': case 'F': val = 15; break;
384 case 'e': case 'E': val = 14; break;
385 case 'd': case 'D': val = 13; break;
386 case 'c': case 'C': val = 12; break;
387 case 'b': case 'B': val = 11; break;
388 case 'a': case 'A': val = 10; break;
389 case '9': val = 9; break;
390 case '8': val = 8; break;
391 case '7': val = 7; break;
392 case '6': val = 6; break;
393 case '5': val = 5; break;
394 case '4': val = 4; break;
395 case '3': val = 3; break;
396 case '2': val = 2; break;
397 case '1': val = 1; break;
398 case '0': val = 0; break;
399 default: return -EINVAL;
411 return even ? OK : -EINVAL;
414 static const char* kLookup = "0123456789abcdef";
416 status_t StrToHex(const std::string& str, std::string& hex) {
418 for (size_t i = 0; i < str.size(); i++) {
419 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
420 hex.push_back(kLookup[str[i] & 0x0F]);
425 status_t NormalizeHex(const std::string& in, std::string& out) {
427 if (HexToStr(in, tmp)) {
430 return StrToHex(tmp, out);
433 uint64_t GetFreeBytes(const std::string& path) {
435 if (statvfs(path.c_str(), &sb) == 0) {
436 return (uint64_t) sb.f_bavail * sb.f_frsize;
442 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
443 // eventually be migrated into system/
444 static int64_t stat_size(struct stat *s) {
445 int64_t blksize = s->st_blksize;
446 // count actual blocks used instead of nominal file size
447 int64_t size = s->st_blocks * 512;
450 /* round up to filesystem block size */
451 size = (size + blksize - 1) & (~(blksize - 1));
457 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
458 // eventually be migrated into system/
459 int64_t calculate_dir_size(int dfd) {
471 while ((de = readdir(d))) {
472 const char *name = de->d_name;
473 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
474 size += stat_size(&s);
476 if (de->d_type == DT_DIR) {
479 /* always skip "." and ".." */
480 if (name[0] == '.') {
483 if ((name[1] == '.') && (name[2] == 0))
487 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
489 size += calculate_dir_size(subfd);
497 uint64_t GetTreeBytes(const std::string& path) {
498 int dirfd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
500 PLOG(WARNING) << "Failed to open " << path;
503 uint64_t res = calculate_dir_size(dirfd);
509 bool IsFilesystemSupported(const std::string& fsType) {
510 std::string supported;
511 if (!ReadFileToString(kProcFilesystems, &supported)) {
512 PLOG(ERROR) << "Failed to read supported filesystems";
515 return supported.find(fsType + "\n") != std::string::npos;
518 status_t WipeBlockDevice(const std::string& path) {
520 const char* c_path = path.c_str();
521 unsigned long nr_sec = 0;
522 unsigned long long range[2];
524 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
526 PLOG(ERROR) << "Failed to open " << path;
530 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
531 PLOG(ERROR) << "Failed to determine size of " << path;
536 range[1] = (unsigned long long) nr_sec * 512;
538 LOG(INFO) << "About to discard " << range[1] << " on " << path;
539 if (ioctl(fd, BLKDISCARD, &range) == 0) {
540 LOG(INFO) << "Discard success on " << path;
543 PLOG(ERROR) << "Discard failure on " << path;
551 static bool isValidFilename(const std::string& name) {
552 if (name.empty() || (name == ".") || (name == "..")
553 || (name.find('/') != std::string::npos)) {
560 std::string BuildKeyPath(const std::string& partGuid) {
561 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
564 std::string BuildDataSystemLegacyPath(userid_t userId) {
565 return StringPrintf("%s/system/users/%u", BuildDataPath(nullptr).c_str(), userId);
568 std::string BuildDataSystemCePath(userid_t userId) {
569 return StringPrintf("%s/system_ce/%u", BuildDataPath(nullptr).c_str(), userId);
572 std::string BuildDataSystemDePath(userid_t userId) {
573 return StringPrintf("%s/system_de/%u", BuildDataPath(nullptr).c_str(), userId);
576 std::string BuildDataMiscLegacyPath(userid_t userId) {
577 return StringPrintf("%s/misc/user/%u", BuildDataPath(nullptr).c_str(), userId);
580 std::string BuildDataMiscCePath(userid_t userId) {
581 return StringPrintf("%s/misc_ce/%u", BuildDataPath(nullptr).c_str(), userId);
584 std::string BuildDataMiscDePath(userid_t userId) {
585 return StringPrintf("%s/misc_de/%u", BuildDataPath(nullptr).c_str(), userId);
588 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
589 std::string BuildDataProfilesDePath(userid_t userId) {
590 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath(nullptr).c_str(), userId);
593 std::string BuildDataPath(const char* volumeUuid) {
594 // TODO: unify with installd path generation logic
595 if (volumeUuid == nullptr) {
598 CHECK(isValidFilename(volumeUuid));
599 return StringPrintf("/mnt/expand/%s", volumeUuid);
603 std::string BuildDataMediaCePath(const char* volumeUuid, userid_t userId) {
604 // TODO: unify with installd path generation logic
605 std::string data(BuildDataPath(volumeUuid));
606 return StringPrintf("%s/media/%u", data.c_str(), userId);
609 std::string BuildDataUserCePath(const char* volumeUuid, userid_t userId) {
610 // TODO: unify with installd path generation logic
611 std::string data(BuildDataPath(volumeUuid));
612 if (volumeUuid == nullptr && userId == 0) {
613 std::string legacy = StringPrintf("%s/data", data.c_str());
615 if (lstat(legacy.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
616 /* /data/data is dir, return /data/data for legacy system */
620 return StringPrintf("%s/user/%u", data.c_str(), userId);
623 std::string BuildDataUserDePath(const char* volumeUuid, userid_t userId) {
624 // TODO: unify with installd path generation logic
625 std::string data(BuildDataPath(volumeUuid));
626 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
629 dev_t GetDevice(const std::string& path) {
631 if (stat(path.c_str(), &sb)) {
632 PLOG(WARNING) << "Failed to stat " << path;
639 status_t RestoreconRecursive(const std::string& path) {
640 LOG(VERBOSE) << "Starting restorecon of " << path;
642 static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
644 android::base::SetProperty(kRestoreconString, "");
645 android::base::SetProperty(kRestoreconString, path);
647 android::base::WaitForProperty(kRestoreconString, path);
649 LOG(VERBOSE) << "Finished restorecon of " << path;
653 status_t SaneReadLinkAt(int dirfd, const char* path, char* buf, size_t bufsiz) {
654 ssize_t len = readlinkat(dirfd, path, buf, bufsiz);
657 } else if (len == (ssize_t) bufsiz) {
665 bool IsRunningInEmulator() {
666 return android::base::GetBoolProperty("ro.kernel.qemu", false);
670 } // namespace android