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/stringprintf.h>
24 #include <cutils/fs.h>
25 #include <cutils/properties.h>
26 #include <private/android_filesystem_config.h>
27 #include <logwrap/logwrap.h>
34 #include <sys/mount.h>
35 #include <sys/types.h>
38 #include <sys/statvfs.h>
40 #ifndef UMOUNT_NOFOLLOW
41 #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
44 using android::base::ReadFileToString;
45 using android::base::StringPrintf;
50 security_context_t sBlkidContext = nullptr;
51 security_context_t sBlkidUntrustedContext = nullptr;
52 security_context_t sFsckContext = nullptr;
53 security_context_t sFsckUntrustedContext = nullptr;
55 static const char* kBlkidPath = "/system/bin/blkid";
56 static const char* kKeyPath = "/data/misc/vold";
58 static const char* kProcFilesystems = "/proc/filesystems";
60 status_t CreateDeviceNode(const std::string& path, dev_t dev) {
61 const char* cpath = path.c_str();
64 char* secontext = nullptr;
66 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFBLK)) {
67 setfscreatecon(secontext);
71 mode_t mode = 0660 | S_IFBLK;
72 if (mknod(cpath, mode, dev) < 0) {
73 if (errno != EEXIST) {
74 PLOG(ERROR) << "Failed to create device node for " << major(dev)
75 << ":" << minor(dev) << " at " << path;
81 setfscreatecon(nullptr);
88 status_t DestroyDeviceNode(const std::string& path) {
89 const char* cpath = path.c_str();
90 if (TEMP_FAILURE_RETRY(unlink(cpath))) {
97 status_t PrepareDir(const std::string& path, mode_t mode, uid_t uid, gid_t gid) {
98 const char* cpath = path.c_str();
100 char* secontext = nullptr;
102 if (!selabel_lookup(sehandle, &secontext, cpath, S_IFDIR)) {
103 setfscreatecon(secontext);
107 int res = fs_prepare_dir(cpath, mode, uid, gid);
110 setfscreatecon(nullptr);
121 status_t ForceUnmount(const std::string& path) {
122 const char* cpath = path.c_str();
123 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
126 // Apps might still be handling eject request, so wait before
127 // we start sending signals
130 Process::killProcessesWithOpenFiles(cpath, SIGINT);
132 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
136 Process::killProcessesWithOpenFiles(cpath, SIGTERM);
138 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
142 Process::killProcessesWithOpenFiles(cpath, SIGKILL);
144 if (!umount2(cpath, UMOUNT_NOFOLLOW) || errno == EINVAL || errno == ENOENT) {
151 status_t KillProcessesUsingPath(const std::string& path) {
152 const char* cpath = path.c_str();
153 if (Process::killProcessesWithOpenFiles(cpath, SIGINT) == 0) {
158 if (Process::killProcessesWithOpenFiles(cpath, SIGTERM) == 0) {
163 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
168 // Send SIGKILL a second time to determine if we've
169 // actually killed everyone with open files
170 if (Process::killProcessesWithOpenFiles(cpath, SIGKILL) == 0) {
173 PLOG(ERROR) << "Failed to kill processes using " << path;
177 status_t BindMount(const std::string& source, const std::string& target) {
178 if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
179 PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
185 static status_t readMetadata(const std::string& path, std::string& fsType,
186 std::string& fsUuid, std::string& fsLabel, bool untrusted) {
191 std::vector<std::string> cmd;
192 cmd.push_back(kBlkidPath);
194 cmd.push_back("/dev/null");
196 cmd.push_back("TYPE");
198 cmd.push_back("UUID");
200 cmd.push_back("LABEL");
203 std::vector<std::string> output;
204 status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
206 LOG(WARNING) << "blkid failed to identify " << path;
211 for (auto line : output) {
212 // Extract values from blkid output, if defined
213 const char* cline = line.c_str();
214 const char* start = strstr(cline, "TYPE=");
215 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
219 start = strstr(cline, "UUID=");
220 if (start != nullptr && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
224 start = strstr(cline, "LABEL=");
225 if (start != nullptr && sscanf(start + 6, "\"%127[^\"]\"", value) == 1) {
233 status_t ReadMetadata(const std::string& path, std::string& fsType,
234 std::string& fsUuid, std::string& fsLabel) {
235 return readMetadata(path, fsType, fsUuid, fsLabel, false);
238 status_t ReadMetadataUntrusted(const std::string& path, std::string& fsType,
239 std::string& fsUuid, std::string& fsLabel) {
240 return readMetadata(path, fsType, fsUuid, fsLabel, true);
243 status_t ForkExecvp(const std::vector<std::string>& args) {
244 return ForkExecvp(args, nullptr);
247 status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
248 size_t argc = args.size();
249 char** argv = (char**) calloc(argc, sizeof(char*));
250 for (size_t i = 0; i < argc; i++) {
251 argv[i] = (char*) args[i].c_str();
253 LOG(VERBOSE) << args[i];
255 LOG(VERBOSE) << " " << args[i];
259 if (setexeccon(context)) {
260 LOG(ERROR) << "Failed to setexeccon";
263 status_t res = android_fork_execvp(argc, argv, NULL, false, true);
264 if (setexeccon(nullptr)) {
265 LOG(ERROR) << "Failed to setexeccon";
273 status_t ForkExecvp(const std::vector<std::string>& args,
274 std::vector<std::string>& output) {
275 return ForkExecvp(args, output, nullptr);
278 status_t ForkExecvp(const std::vector<std::string>& args,
279 std::vector<std::string>& output, security_context_t context) {
281 for (size_t i = 0; i < args.size(); i++) {
282 cmd += args[i] + " ";
284 LOG(VERBOSE) << args[i];
286 LOG(VERBOSE) << " " << args[i];
291 if (setexeccon(context)) {
292 LOG(ERROR) << "Failed to setexeccon";
295 FILE* fp = popen(cmd.c_str(), "r");
296 if (setexeccon(nullptr)) {
297 LOG(ERROR) << "Failed to setexeccon";
302 PLOG(ERROR) << "Failed to popen " << cmd;
306 while (fgets(line, sizeof(line), fp) != nullptr) {
307 LOG(VERBOSE) << line;
308 output.push_back(std::string(line));
310 if (pclose(fp) != 0) {
311 PLOG(ERROR) << "Failed to pclose " << cmd;
318 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
319 size_t argc = args.size();
320 char** argv = (char**) calloc(argc + 1, sizeof(char*));
321 for (size_t i = 0; i < argc; i++) {
322 argv[i] = (char*) args[i].c_str();
324 LOG(VERBOSE) << args[i];
326 LOG(VERBOSE) << " " << args[i];
333 close(STDOUT_FILENO);
334 close(STDERR_FILENO);
336 if (execvp(argv[0], argv)) {
337 PLOG(ERROR) << "Failed to exec";
344 PLOG(ERROR) << "Failed to exec";
351 status_t ReadRandomBytes(size_t bytes, std::string& out) {
354 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
361 while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], std::min(sizeof(buf), bytes)))) > 0) {
374 status_t HexToStr(const std::string& hex, std::string& str) {
378 for (size_t i = 0; i < hex.size(); i++) {
381 case ' ': case '-': case ':': continue;
382 case 'f': case 'F': val = 15; break;
383 case 'e': case 'E': val = 14; break;
384 case 'd': case 'D': val = 13; break;
385 case 'c': case 'C': val = 12; break;
386 case 'b': case 'B': val = 11; break;
387 case 'a': case 'A': val = 10; break;
388 case '9': val = 9; break;
389 case '8': val = 8; break;
390 case '7': val = 7; break;
391 case '6': val = 6; break;
392 case '5': val = 5; break;
393 case '4': val = 4; break;
394 case '3': val = 3; break;
395 case '2': val = 2; break;
396 case '1': val = 1; break;
397 case '0': val = 0; break;
398 default: return -EINVAL;
410 return even ? OK : -EINVAL;
413 static const char* kLookup = "0123456789abcdef";
415 status_t StrToHex(const std::string& str, std::string& hex) {
417 for (size_t i = 0; i < str.size(); i++) {
418 hex.push_back(kLookup[(str[i] & 0xF0) >> 4]);
419 hex.push_back(kLookup[str[i] & 0x0F]);
424 status_t NormalizeHex(const std::string& in, std::string& out) {
426 if (HexToStr(in, tmp)) {
429 return StrToHex(tmp, out);
432 uint64_t GetFreeBytes(const std::string& path) {
434 if (statvfs(path.c_str(), &sb) == 0) {
435 return (uint64_t)sb.f_bfree * sb.f_bsize;
441 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
442 // eventually be migrated into system/
443 static int64_t stat_size(struct stat *s) {
444 int64_t blksize = s->st_blksize;
445 // count actual blocks used instead of nominal file size
446 int64_t size = s->st_blocks * 512;
449 /* round up to filesystem block size */
450 size = (size + blksize - 1) & (~(blksize - 1));
456 // TODO: borrowed from frameworks/native/libs/diskusage/ which should
457 // eventually be migrated into system/
458 int64_t calculate_dir_size(int dfd) {
470 while ((de = readdir(d))) {
471 const char *name = de->d_name;
472 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
473 size += stat_size(&s);
475 if (de->d_type == DT_DIR) {
478 /* always skip "." and ".." */
479 if (name[0] == '.') {
482 if ((name[1] == '.') && (name[2] == 0))
486 subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
488 size += calculate_dir_size(subfd);
496 uint64_t GetTreeBytes(const std::string& path) {
497 int dirfd = open(path.c_str(), O_DIRECTORY, O_RDONLY);
499 PLOG(WARNING) << "Failed to open " << path;
502 uint64_t res = calculate_dir_size(dirfd);
508 bool IsFilesystemSupported(const std::string& fsType) {
509 std::string supported;
510 if (!ReadFileToString(kProcFilesystems, &supported)) {
511 PLOG(ERROR) << "Failed to read supported filesystems";
514 return supported.find(fsType + "\n") != std::string::npos;
517 status_t WipeBlockDevice(const std::string& path) {
519 const char* c_path = path.c_str();
520 unsigned long nr_sec = 0;
521 unsigned long long range[2];
523 int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
525 PLOG(ERROR) << "Failed to open " << path;
529 if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
530 PLOG(ERROR) << "Failed to determine size of " << path;
535 range[1] = (unsigned long long) nr_sec * 512;
537 LOG(INFO) << "About to discard " << range[1] << " on " << path;
538 if (ioctl(fd, BLKDISCARD, &range) == 0) {
539 LOG(INFO) << "Discard success on " << path;
542 PLOG(ERROR) << "Discard failure on " << path;
550 static bool isValidFilename(const std::string& name) {
551 if (name.empty() || (name == ".") || (name == "..")
552 || (name.find('/') != std::string::npos)) {
559 std::string BuildKeyPath(const std::string& partGuid) {
560 return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
563 std::string BuildDataSystemLegacyPath(userid_t userId) {
564 return StringPrintf("%s/system/users/%u", BuildDataPath(nullptr).c_str(), userId);
567 std::string BuildDataSystemCePath(userid_t userId) {
568 return StringPrintf("%s/system_ce/%u", BuildDataPath(nullptr).c_str(), userId);
571 std::string BuildDataSystemDePath(userid_t userId) {
572 return StringPrintf("%s/system_de/%u", BuildDataPath(nullptr).c_str(), userId);
575 std::string BuildDataMiscLegacyPath(userid_t userId) {
576 return StringPrintf("%s/misc/user/%u", BuildDataPath(nullptr).c_str(), userId);
579 std::string BuildDataMiscCePath(userid_t userId) {
580 return StringPrintf("%s/misc_ce/%u", BuildDataPath(nullptr).c_str(), userId);
583 std::string BuildDataMiscDePath(userid_t userId) {
584 return StringPrintf("%s/misc_de/%u", BuildDataPath(nullptr).c_str(), userId);
587 // Keep in sync with installd (frameworks/native/cmds/installd/utils.h)
588 std::string BuildDataProfilesDePath(userid_t userId) {
589 return StringPrintf("%s/misc/profiles/cur/%u", BuildDataPath(nullptr).c_str(), userId);
592 std::string BuildDataProfilesForeignDexDePath(userid_t userId) {
593 std::string profiles_path = BuildDataProfilesDePath(userId);
594 return StringPrintf("%s/foreign-dex", profiles_path.c_str());
597 std::string BuildDataPath(const char* volumeUuid) {
598 // TODO: unify with installd path generation logic
599 if (volumeUuid == nullptr) {
602 CHECK(isValidFilename(volumeUuid));
603 return StringPrintf("/mnt/expand/%s", volumeUuid);
607 std::string BuildDataMediaCePath(const char* volumeUuid, userid_t userId) {
608 // TODO: unify with installd path generation logic
609 std::string data(BuildDataPath(volumeUuid));
610 return StringPrintf("%s/media/%u", data.c_str(), userId);
613 std::string BuildDataUserCePath(const char* volumeUuid, userid_t userId) {
614 // TODO: unify with installd path generation logic
615 std::string data(BuildDataPath(volumeUuid));
616 if (volumeUuid == nullptr) {
618 return StringPrintf("%s/data", data.c_str());
620 return StringPrintf("%s/user/%u", data.c_str(), userId);
623 return StringPrintf("%s/user/%u", data.c_str(), userId);
627 std::string BuildDataUserDePath(const char* volumeUuid, userid_t userId) {
628 // TODO: unify with installd path generation logic
629 std::string data(BuildDataPath(volumeUuid));
630 return StringPrintf("%s/user_de/%u", data.c_str(), userId);
633 dev_t GetDevice(const std::string& path) {
635 if (stat(path.c_str(), &sb)) {
636 PLOG(WARNING) << "Failed to stat " << path;
643 std::string DefaultFstabPath() {
644 char hardware[PROPERTY_VALUE_MAX];
645 property_get("ro.hardware", hardware, "");
646 return StringPrintf("/fstab.%s", hardware);
649 status_t RestoreconRecursive(const std::string& path) {
650 LOG(VERBOSE) << "Starting restorecon of " << path;
652 // TODO: find a cleaner way of waiting for restorecon to finish
653 const char* cpath = path.c_str();
654 property_set("selinux.restorecon_recursive", "");
655 property_set("selinux.restorecon_recursive", cpath);
657 char value[PROPERTY_VALUE_MAX];
659 property_get("selinux.restorecon_recursive", value, "");
660 if (strcmp(cpath, value) == 0) {
663 usleep(100000); // 100ms
666 LOG(VERBOSE) << "Finished restorecon of " << path;
670 status_t SaneReadLinkAt(int dirfd, const char* path, char* buf, size_t bufsiz) {
671 ssize_t len = readlinkat(dirfd, path, buf, bufsiz);
674 } else if (len == (ssize_t) bufsiz) {
682 ScopedFd::ScopedFd(int fd) : fd_(fd) {}
684 ScopedFd::~ScopedFd() {
688 ScopedDir::ScopedDir(DIR* dir) : dir_(dir) {}
690 ScopedDir::~ScopedDir() {
691 if (dir_ != nullptr) {
696 bool IsRunningInEmulator() {
697 return property_get_bool("ro.kernel.qemu", 0);
701 } // namespace android