[automerger skipped] Fsync directories before delete key
am: a598e04a91 -s ours
am skip reason: change_id Ib8c349d6d033f86b247f4b35b8354d97cf249d26 with SHA1 37c82f5c0f is in history
Change-Id: Ifec2d700dbe6bbe55e65e6e07003d1e77fb3dbc2
diff --git a/Android.bp b/Android.bp
index 556784f..1045dc2 100644
--- a/Android.bp
+++ b/Android.bp
@@ -17,6 +17,7 @@
"-*",
"cert-*",
"clang-analyzer-security*",
+ "android-*",
],
tidy_flags: [
"-warnings-as-errors=clang-analyzer-security*,cert-*",
@@ -31,6 +32,7 @@
"libbootloader_message",
"libfec",
"libfec_rs",
+ "libfs_avb",
"libfs_mgr",
"libscrypt_static",
"libsquashfs_utils",
@@ -39,6 +41,7 @@
shared_libs: [
"android.hardware.keymaster@3.0",
"android.hardware.keymaster@4.0",
+ "android.hardware.boot@1.0",
"libbase",
"libbinder",
"libcrypto",
@@ -47,6 +50,7 @@
"libdiskconfig",
"libext4_utils",
"libf2fs_sparseblock",
+ "libfscrypt",
"libhardware",
"libhardware_legacy",
"libhidlbase",
@@ -93,12 +97,14 @@
],
srcs: [
+ "AppFuseUtil.cpp",
"Benchmark.cpp",
"CheckEncryption.cpp",
+ "Checkpoint.cpp",
"Devmapper.cpp",
"EncryptInplace.cpp",
- "Ext4Crypt.cpp",
"FileDeviceUtils.cpp",
+ "FsCrypt.cpp",
"IdleMaint.cpp",
"KeyBuffer.cpp",
"KeyStorage.cpp",
@@ -126,19 +132,30 @@
"model/PrivateVolume.cpp",
"model/PublicVolume.cpp",
"model/VolumeBase.cpp",
- "secontext.cpp",
+ "model/StubVolume.cpp",
],
product_variables: {
arc: {
exclude_srcs: [
+ "AppFuseUtil.cpp",
"model/ObbVolume.cpp",
],
static_libs: [
"arc_services_aidl",
+ "libarcappfuse",
"libarcobbvolume",
],
},
+ debuggable: {
+ cppflags: ["-D__ANDROID_DEBUGGABLE__"],
+ },
},
+ shared_libs: [
+ "android.hardware.health.storage@1.0",
+ ],
+ whole_static_libs: [
+ "com.android.sysprop.apex",
+ ],
}
cc_binary {
@@ -154,6 +171,7 @@
arc: {
static_libs: [
"arc_services_aidl",
+ "libarcappfuse",
"libarcobbvolume",
],
},
@@ -168,6 +186,11 @@
"vold_prepare_subdirs",
"wait_for_keymaster",
],
+
+ shared_libs: [
+ "android.hardware.health.storage@1.0",
+ "libhidltransport",
+ ],
}
cc_binary {
diff --git a/AppFuseUtil.cpp b/AppFuseUtil.cpp
new file mode 100644
index 0000000..711e70b
--- /dev/null
+++ b/AppFuseUtil.cpp
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "AppFuseUtil.h"
+
+#include <sys/mount.h>
+#include <utils/Errors.h>
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+
+#include "Utils.h"
+
+using android::base::StringPrintf;
+
+namespace android {
+namespace vold {
+
+namespace {
+
+static size_t kAppFuseMaxMountPointName = 32;
+
+static android::status_t GetMountPath(uid_t uid, const std::string& name, std::string* path) {
+ if (name.size() > kAppFuseMaxMountPointName) {
+ LOG(ERROR) << "AppFuse mount name is too long.";
+ return -EINVAL;
+ }
+ for (size_t i = 0; i < name.size(); i++) {
+ if (!isalnum(name[i])) {
+ LOG(ERROR) << "AppFuse mount name contains invalid character.";
+ return -EINVAL;
+ }
+ }
+ *path = StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
+ return android::OK;
+}
+
+static android::status_t Mount(int device_fd, const std::string& path) {
+ const auto opts = StringPrintf(
+ "fd=%i,"
+ "rootmode=40000,"
+ "default_permissions,"
+ "allow_other,"
+ "user_id=0,group_id=0,"
+ "context=\"u:object_r:app_fuse_file:s0\","
+ "fscontext=u:object_r:app_fusefs:s0",
+ device_fd);
+
+ const int result =
+ TEMP_FAILURE_RETRY(mount("/dev/fuse", path.c_str(), "fuse",
+ MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
+ if (result != 0) {
+ PLOG(ERROR) << "Failed to mount " << path;
+ return -errno;
+ }
+
+ return android::OK;
+}
+
+static android::status_t RunCommand(const std::string& command, uid_t uid, const std::string& path,
+ int device_fd) {
+ if (DEBUG_APPFUSE) {
+ LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path << " and uid "
+ << uid;
+ }
+
+ if (command == "mount") {
+ return Mount(device_fd, path);
+ } else if (command == "unmount") {
+ // If it's just after all FD opened on mount point are closed, umount2 can fail with
+ // EBUSY. To avoid the case, specify MNT_DETACH.
+ if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 && errno != EINVAL &&
+ errno != ENOENT) {
+ PLOG(ERROR) << "Failed to unmount directory.";
+ return -errno;
+ }
+ if (rmdir(path.c_str()) != 0) {
+ PLOG(ERROR) << "Failed to remove the mount directory.";
+ return -errno;
+ }
+ return android::OK;
+ } else {
+ LOG(ERROR) << "Unknown appfuse command " << command;
+ return -EPERM;
+ }
+
+ return android::OK;
+}
+
+} // namespace
+
+int MountAppFuse(uid_t uid, int mountId, android::base::unique_fd* device_fd) {
+ std::string name = std::to_string(mountId);
+
+ // Check mount point name.
+ std::string path;
+ if (GetMountPath(uid, name, &path) != android::OK) {
+ LOG(ERROR) << "Invalid mount point name";
+ return -1;
+ }
+
+ // Forcibly remove the existing mount before we attempt to prepare the
+ // directory. If we have a dangling mount, then PrepareDir may fail if the
+ // indirection to FUSE doesn't work.
+ android::vold::ForceUnmount(path);
+
+ // Create directories.
+ const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
+ if (result != android::OK) {
+ PLOG(ERROR) << "Failed to prepare directory " << path;
+ return -1;
+ }
+
+ // Open device FD.
+ // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
+ device_fd->reset(open("/dev/fuse", O_RDWR));
+ if (device_fd->get() == -1) {
+ PLOG(ERROR) << "Failed to open /dev/fuse";
+ return -1;
+ }
+
+ // Mount.
+ return RunCommand("mount", uid, path, device_fd->get());
+}
+
+int UnmountAppFuse(uid_t uid, int mountId) {
+ std::string name = std::to_string(mountId);
+
+ // Check mount point name.
+ std::string path;
+ if (GetMountPath(uid, name, &path) != android::OK) {
+ LOG(ERROR) << "Invalid mount point name";
+ return -1;
+ }
+
+ return RunCommand("unmount", uid, path, -1 /* device_fd */);
+}
+
+int OpenAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
+ std::string name = std::to_string(mountId);
+
+ // Check mount point name.
+ std::string mountPoint;
+ if (GetMountPath(uid, name, &mountPoint) != android::OK) {
+ LOG(ERROR) << "Invalid mount point name";
+ return -1;
+ }
+
+ std::string path = StringPrintf("%s/%d", mountPoint.c_str(), fileId);
+ return TEMP_FAILURE_RETRY(open(path.c_str(), flags));
+}
+
+} // namespace vold
+} // namespace android
diff --git a/AppFuseUtil.h b/AppFuseUtil.h
new file mode 100644
index 0000000..463c6d0
--- /dev/null
+++ b/AppFuseUtil.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_VOLD_APP_FUSE_UTIL_H_
+#define ANDROID_VOLD_APP_FUSE_UTIL_H_
+
+#include <android-base/unique_fd.h>
+
+#define DEBUG_APPFUSE 0
+
+namespace android {
+namespace vold {
+
+int MountAppFuse(uid_t uid, int mountId, android::base::unique_fd* device_fd);
+
+int UnmountAppFuse(uid_t uid, int mountId);
+
+int OpenAppFuseFile(uid_t uid, int mountId, int fileId, int flags);
+
+} // namespace vold
+} // namespace android
+
+#endif // ANDROID_VOLD_APP_FUSE_UTIL_H_
diff --git a/Benchmark.cpp b/Benchmark.cpp
index dfe3366..b0a3b85 100644
--- a/Benchmark.cpp
+++ b/Benchmark.cpp
@@ -28,8 +28,8 @@
#include <thread>
-#include <sys/time.h>
#include <sys/resource.h>
+#include <sys/time.h>
#include <unistd.h>
using android::base::ReadFileToString;
@@ -50,12 +50,12 @@
// RAII class for boosting device performance during benchmarks.
class PerformanceBoost {
-private:
+ private:
int orig_prio;
int orig_ioprio;
IoSchedClass orig_clazz;
-public:
+ public:
PerformanceBoost() {
errno = 0;
orig_prio = getpriority(PRIO_PROCESS, 0);
@@ -87,8 +87,8 @@
};
static status_t benchmarkInternal(const std::string& rootPath,
- const android::sp<android::os::IVoldTaskListener>& listener,
- android::os::PersistableBundle* extras) {
+ const android::sp<android::os::IVoldTaskListener>& listener,
+ android::os::PersistableBundle* extras) {
status_t res = 0;
auto path = rootPath;
@@ -137,12 +137,12 @@
// Only drop when we haven't aborted
if (res == OK) {
android::base::Timer timer;
- LOG(VERBOSE) << "Before drop_caches";
+ LOG(DEBUG) << "Before drop_caches";
if (!WriteStringToFile("3", "/proc/sys/vm/drop_caches")) {
PLOG(ERROR) << "Failed to drop_caches";
res = -1;
}
- LOG(VERBOSE) << "After drop_caches";
+ LOG(DEBUG) << "After drop_caches";
sync();
if (res == OK) extras->putLong(String16("drop"), timer.duration().count());
}
@@ -179,7 +179,7 @@
}
void Benchmark(const std::string& path,
- const android::sp<android::os::IVoldTaskListener>& listener) {
+ const android::sp<android::os::IVoldTaskListener>& listener) {
std::lock_guard<std::mutex> lock(kBenchmarkLock);
acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
diff --git a/Benchmark.h b/Benchmark.h
index 4f19b01..d5882cd 100644
--- a/Benchmark.h
+++ b/Benchmark.h
@@ -24,8 +24,10 @@
namespace android {
namespace vold {
+// clang-format off
void Benchmark(const std::string& path,
- const android::sp<android::os::IVoldTaskListener>& listener);
+ const android::sp<android::os::IVoldTaskListener>& listener);
+// clang-format on
} // namespace vold
} // namespace android
diff --git a/Checkpoint.cpp b/Checkpoint.cpp
new file mode 100644
index 0000000..e784c91
--- /dev/null
+++ b/Checkpoint.cpp
@@ -0,0 +1,711 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "Checkpoint"
+#include "Checkpoint.h"
+#include "VoldUtil.h"
+
+#include <fstream>
+#include <list>
+#include <memory>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/parseint.h>
+#include <android-base/properties.h>
+#include <android-base/unique_fd.h>
+#include <android/hardware/boot/1.0/IBootControl.h>
+#include <cutils/android_reboot.h>
+#include <fcntl.h>
+#include <fs_mgr.h>
+#include <linux/fs.h>
+#include <mntent.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/statvfs.h>
+#include <unistd.h>
+
+using android::base::GetBoolProperty;
+using android::base::GetUintProperty;
+using android::base::SetProperty;
+using android::binder::Status;
+using android::fs_mgr::Fstab;
+using android::fs_mgr::ReadDefaultFstab;
+using android::fs_mgr::ReadFstabFromFile;
+using android::hardware::hidl_string;
+using android::hardware::boot::V1_0::BoolResult;
+using android::hardware::boot::V1_0::CommandResult;
+using android::hardware::boot::V1_0::IBootControl;
+using android::hardware::boot::V1_0::Slot;
+
+namespace android {
+namespace vold {
+
+namespace {
+const std::string kMetadataCPFile = "/metadata/vold/checkpoint";
+
+bool setBowState(std::string const& block_device, std::string const& state) {
+ if (block_device.substr(0, 5) != "/dev/") {
+ LOG(ERROR) << "Expected block device, got " << block_device;
+ return false;
+ }
+
+ std::string state_filename = std::string("/sys/") + block_device.substr(5) + "/bow/state";
+ if (!android::base::WriteStringToFile(state, state_filename)) {
+ PLOG(ERROR) << "Failed to write to file " << state_filename;
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace
+
+Status cp_supportsCheckpoint(bool& result) {
+ result = false;
+
+ for (const auto& entry : fstab_default) {
+ if (entry.fs_mgr_flags.checkpoint_blk || entry.fs_mgr_flags.checkpoint_fs) {
+ result = true;
+ return Status::ok();
+ }
+ }
+ return Status::ok();
+}
+
+Status cp_supportsBlockCheckpoint(bool& result) {
+ result = false;
+
+ for (const auto& entry : fstab_default) {
+ if (entry.fs_mgr_flags.checkpoint_blk) {
+ result = true;
+ return Status::ok();
+ }
+ }
+ return Status::ok();
+}
+
+Status cp_supportsFileCheckpoint(bool& result) {
+ result = false;
+
+ for (const auto& entry : fstab_default) {
+ if (entry.fs_mgr_flags.checkpoint_fs) {
+ result = true;
+ return Status::ok();
+ }
+ }
+ return Status::ok();
+}
+
+Status cp_startCheckpoint(int retry) {
+ if (retry < -1) return Status::fromExceptionCode(EINVAL, "Retry count must be more than -1");
+ std::string content = std::to_string(retry + 1);
+ if (retry == -1) {
+ sp<IBootControl> module = IBootControl::getService();
+ if (module) {
+ std::string suffix;
+ auto cb = [&suffix](hidl_string s) { suffix = s; };
+ if (module->getSuffix(module->getCurrentSlot(), cb).isOk()) content += " " + suffix;
+ }
+ }
+ if (!android::base::WriteStringToFile(content, kMetadataCPFile))
+ return Status::fromExceptionCode(errno, "Failed to write checkpoint file");
+ return Status::ok();
+}
+
+namespace {
+
+volatile bool isCheckpointing = false;
+}
+
+Status cp_commitChanges() {
+ if (!isCheckpointing) {
+ return Status::ok();
+ }
+ sp<IBootControl> module = IBootControl::getService();
+ if (module) {
+ CommandResult cr;
+ module->markBootSuccessful([&cr](CommandResult result) { cr = result; });
+ if (!cr.success) {
+ std::string msg = "Error marking booted successfully: " + std::string(cr.errMsg);
+ return Status::fromExceptionCode(EINVAL, String8(msg.c_str()));
+ }
+ LOG(INFO) << "Marked slot as booted successfully.";
+ }
+ // Must take action for list of mounted checkpointed things here
+ // To do this, we walk the list of mounted file systems.
+ // But we also need to get the matching fstab entries to see
+ // the original flags
+ std::string err_str;
+
+ Fstab mounts;
+ if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
+ return Status::fromExceptionCode(EINVAL, "Failed to get /proc/mounts");
+ }
+
+ // Walk mounted file systems
+ for (const auto& mount_rec : mounts) {
+ const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point);
+ if (!fstab_rec) continue;
+
+ if (fstab_rec->fs_mgr_flags.checkpoint_fs) {
+ if (fstab_rec->fs_type == "f2fs") {
+ std::string options = mount_rec.fs_options + ",checkpoint=enable";
+ if (mount(mount_rec.blk_device.c_str(), mount_rec.mount_point.c_str(), "none",
+ MS_REMOUNT | fstab_rec->flags, options.c_str())) {
+ return Status::fromExceptionCode(EINVAL, "Failed to remount");
+ }
+ }
+ } else if (fstab_rec->fs_mgr_flags.checkpoint_blk) {
+ if (!setBowState(mount_rec.blk_device, "2"))
+ return Status::fromExceptionCode(EINVAL, "Failed to set bow state");
+ }
+ }
+ SetProperty("vold.checkpoint_committed", "1");
+ LOG(INFO) << "Checkpoint has been committed.";
+ isCheckpointing = false;
+ if (!android::base::RemoveFileIfExists(kMetadataCPFile, &err_str))
+ return Status::fromExceptionCode(errno, err_str.c_str());
+ return Status::ok();
+}
+
+namespace {
+void abort_metadata_file() {
+ std::string oldContent, newContent;
+ int retry = 0;
+ struct stat st;
+ int result = stat(kMetadataCPFile.c_str(), &st);
+
+ // If the file doesn't exist, we aren't managing a checkpoint retry counter
+ if (result != 0) return;
+ if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) {
+ PLOG(ERROR) << "Failed to read checkpoint file";
+ return;
+ }
+ std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" "));
+
+ if (!android::base::ParseInt(retryContent, &retry)) {
+ PLOG(ERROR) << "Could not parse retry count";
+ return;
+ }
+ if (retry > 0) {
+ newContent = "0";
+ if (!android::base::WriteStringToFile(newContent, kMetadataCPFile))
+ PLOG(ERROR) << "Could not write checkpoint file";
+ }
+}
+} // namespace
+
+void cp_abortChanges(const std::string& message, bool retry) {
+ if (!cp_needsCheckpoint()) return;
+ if (!retry) abort_metadata_file();
+ android_reboot(ANDROID_RB_RESTART2, 0, message.c_str());
+}
+
+bool cp_needsRollback() {
+ std::string content;
+ bool ret;
+
+ ret = android::base::ReadFileToString(kMetadataCPFile, &content);
+ if (ret) {
+ if (content == "0") return true;
+ if (content.substr(0, 3) == "-1 ") {
+ std::string oldSuffix = content.substr(3);
+ sp<IBootControl> module = IBootControl::getService();
+ std::string newSuffix;
+
+ if (module) {
+ auto cb = [&newSuffix](hidl_string s) { newSuffix = s; };
+ module->getSuffix(module->getCurrentSlot(), cb);
+ if (oldSuffix == newSuffix) return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool cp_needsCheckpoint() {
+ bool ret;
+ std::string content;
+ sp<IBootControl> module = IBootControl::getService();
+
+ if (isCheckpointing) return isCheckpointing;
+
+ if (module && module->isSlotMarkedSuccessful(module->getCurrentSlot()) == BoolResult::FALSE) {
+ isCheckpointing = true;
+ return true;
+ }
+ ret = android::base::ReadFileToString(kMetadataCPFile, &content);
+ if (ret) {
+ ret = content != "0";
+ isCheckpointing = ret;
+ return ret;
+ }
+ return false;
+}
+
+namespace {
+const std::string kSleepTimeProp = "ro.sys.cp_msleeptime";
+const uint32_t msleeptime_default = 1000; // 1 s
+const uint32_t max_msleeptime = 3600000; // 1 h
+
+const std::string kMinFreeBytesProp = "ro.sys.cp_min_free_bytes";
+const uint64_t min_free_bytes_default = 100 * (1 << 20); // 100 MiB
+
+const std::string kCommitOnFullProp = "ro.sys.cp_commit_on_full";
+const bool commit_on_full_default = true;
+
+static void cp_healthDaemon(std::string mnt_pnt, std::string blk_device, bool is_fs_cp) {
+ struct statvfs data;
+ uint64_t free_bytes = 0;
+ uint32_t msleeptime = GetUintProperty(kSleepTimeProp, msleeptime_default, max_msleeptime);
+ uint64_t min_free_bytes =
+ GetUintProperty(kMinFreeBytesProp, min_free_bytes_default, (uint64_t)-1);
+ bool commit_on_full = GetBoolProperty(kCommitOnFullProp, commit_on_full_default);
+
+ struct timespec req;
+ req.tv_sec = msleeptime / 1000;
+ msleeptime %= 1000;
+ req.tv_nsec = msleeptime * 1000000;
+ while (isCheckpointing) {
+ if (is_fs_cp) {
+ statvfs(mnt_pnt.c_str(), &data);
+ free_bytes = data.f_bavail * data.f_frsize;
+ } else {
+ int ret;
+ std::string size_filename = std::string("/sys/") + blk_device.substr(5) + "/bow/free";
+ std::string content;
+ ret = android::base::ReadFileToString(size_filename, &content);
+ if (ret) {
+ free_bytes = std::strtoul(content.c_str(), NULL, 10);
+ }
+ }
+ if (free_bytes < min_free_bytes) {
+ if (commit_on_full) {
+ LOG(INFO) << "Low space for checkpointing. Commiting changes";
+ cp_commitChanges();
+ break;
+ } else {
+ LOG(INFO) << "Low space for checkpointing. Rebooting";
+ cp_abortChanges("checkpoint,low_space", false);
+ break;
+ }
+ }
+ nanosleep(&req, NULL);
+ }
+}
+
+} // namespace
+
+Status cp_prepareCheckpoint() {
+ if (!isCheckpointing) {
+ return Status::ok();
+ }
+
+ Fstab mounts;
+ if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
+ return Status::fromExceptionCode(EINVAL, "Failed to get /proc/mounts");
+ }
+
+ for (const auto& mount_rec : mounts) {
+ const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point);
+ if (!fstab_rec) continue;
+
+ if (fstab_rec->fs_mgr_flags.checkpoint_blk) {
+ android::base::unique_fd fd(
+ TEMP_FAILURE_RETRY(open(mount_rec.mount_point.c_str(), O_RDONLY | O_CLOEXEC)));
+ if (fd == -1) {
+ PLOG(ERROR) << "Failed to open mount point" << mount_rec.mount_point;
+ continue;
+ }
+
+ struct fstrim_range range = {};
+ range.len = ULLONG_MAX;
+ if (ioctl(fd, FITRIM, &range)) {
+ PLOG(ERROR) << "Failed to trim " << mount_rec.mount_point;
+ continue;
+ }
+
+ setBowState(mount_rec.blk_device, "1");
+ }
+ if (fstab_rec->fs_mgr_flags.checkpoint_blk || fstab_rec->fs_mgr_flags.checkpoint_fs) {
+ std::thread(cp_healthDaemon, std::string(mount_rec.mount_point),
+ std::string(mount_rec.blk_device),
+ fstab_rec->fs_mgr_flags.checkpoint_fs == 1)
+ .detach();
+ }
+ }
+ return Status::ok();
+}
+
+namespace {
+const int kSectorSize = 512;
+
+typedef uint64_t sector_t;
+
+struct log_entry {
+ sector_t source; // in sectors of size kSectorSize
+ sector_t dest; // in sectors of size kSectorSize
+ uint32_t size; // in bytes
+ uint32_t checksum;
+} __attribute__((packed));
+
+struct log_sector_v1_0 {
+ uint32_t magic;
+ uint16_t header_version;
+ uint16_t header_size;
+ uint32_t block_size;
+ uint32_t count;
+ uint32_t sequence;
+ uint64_t sector0;
+} __attribute__((packed));
+
+// MAGIC is BOW in ascii
+const int kMagic = 0x00574f42;
+// Partially restored MAGIC is WOB in ascii
+const int kPartialRestoreMagic = 0x00424f57;
+
+void crc32(const void* data, size_t n_bytes, uint32_t* crc) {
+ static uint32_t table[0x100] = {
+ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535,
+ 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD,
+ 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D,
+ 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
+ 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
+ 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
+ 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC,
+ 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+ 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB,
+ 0xB6662D3D,
+
+ 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5,
+ 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
+ 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
+ 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
+ 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074,
+ 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC,
+ 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C,
+ 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+ 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B,
+ 0xC0BA6CAD,
+
+ 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
+ 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D,
+ 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D,
+ 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
+ 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4,
+ 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
+ 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C,
+ 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+ 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B,
+ 0x5BDEAE1D,
+
+ 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785,
+ 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D,
+ 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD,
+ 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
+ 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354,
+ 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
+ 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C,
+ 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+ 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
+ 0x2D02EF8D};
+
+ for (size_t i = 0; i < n_bytes; ++i) {
+ *crc ^= ((uint8_t*)data)[i];
+ *crc = table[(uint8_t)*crc] ^ *crc >> 8;
+ }
+}
+
+// A map of relocations.
+// The map must be initialized so that relocations[0] = 0
+// During restore, we replay the log records in reverse, copying from dest to
+// source
+// To validate, we must be able to read the 'dest' sectors as though they had
+// been copied but without actually copying. This map represents how the sectors
+// would have been moved. To read a sector s, find the index <= s and read
+// relocations[index] + s - index
+typedef std::map<sector_t, sector_t> Relocations;
+
+void relocate(Relocations& relocations, sector_t dest, sector_t source, int count) {
+ // Find first one we're equal to or greater than
+ auto s = --relocations.upper_bound(source);
+
+ // Take slice
+ Relocations slice;
+ slice[dest] = source - s->first + s->second;
+ ++s;
+
+ // Add rest of elements
+ for (; s != relocations.end() && s->first < source + count; ++s)
+ slice[dest - source + s->first] = s->second;
+
+ // Split range at end of dest
+ auto dest_end = --relocations.upper_bound(dest + count);
+ relocations[dest + count] = dest + count - dest_end->first + dest_end->second;
+
+ // Remove all elements in [dest, dest + count)
+ relocations.erase(relocations.lower_bound(dest), relocations.lower_bound(dest + count));
+
+ // Add new elements
+ relocations.insert(slice.begin(), slice.end());
+}
+
+// A map of sectors that have been written to.
+// The final entry must always be False.
+// When we restart the restore after an interruption, we must take care that
+// when we copy from dest to source, that the block we copy to was not
+// previously copied from.
+// i e. A->B C->A; If we replay this sequence, we end up copying C->B
+// We must save our partial result whenever we finish a page, or when we copy
+// to a location that was copied from earlier (our source is an earlier dest)
+typedef std::map<sector_t, bool> Used_Sectors;
+
+bool checkCollision(Used_Sectors& used_sectors, sector_t start, sector_t end) {
+ auto second_overlap = used_sectors.upper_bound(start);
+ auto first_overlap = --second_overlap;
+
+ if (first_overlap->second) {
+ return true;
+ } else if (second_overlap != used_sectors.end() && second_overlap->first < end) {
+ return true;
+ }
+ return false;
+}
+
+void markUsed(Used_Sectors& used_sectors, sector_t start, sector_t end) {
+ auto start_pos = used_sectors.insert_or_assign(start, true).first;
+ auto end_pos = used_sectors.insert_or_assign(end, false).first;
+
+ if (start_pos == used_sectors.begin() || !std::prev(start_pos)->second) {
+ start_pos++;
+ }
+ if (std::next(end_pos) != used_sectors.end() && !std::next(end_pos)->second) {
+ end_pos++;
+ }
+ if (start_pos->first < end_pos->first) {
+ used_sectors.erase(start_pos, end_pos);
+ }
+}
+
+// Restores the given log_entry's data from dest -> source
+// If that entry is a log sector, set the magic to kPartialRestoreMagic and flush.
+void restoreSector(int device_fd, Used_Sectors& used_sectors, std::vector<char>& ls_buffer,
+ log_entry* le, std::vector<char>& buffer) {
+ log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]);
+ uint32_t index = le - ((log_entry*)&ls_buffer[ls.header_size]);
+ int count = (le->size - 1) / kSectorSize + 1;
+
+ if (checkCollision(used_sectors, le->source, le->source + count)) {
+ fsync(device_fd);
+ lseek64(device_fd, 0, SEEK_SET);
+ ls.count = index + 1;
+ ls.magic = kPartialRestoreMagic;
+ write(device_fd, &ls_buffer[0], ls.block_size);
+ fsync(device_fd);
+ used_sectors.clear();
+ used_sectors[0] = false;
+ }
+
+ markUsed(used_sectors, le->dest, le->dest + count);
+
+ if (index == 0 && ls.sequence != 0) {
+ log_sector_v1_0* next = reinterpret_cast<log_sector_v1_0*>(&buffer[0]);
+ if (next->magic == kMagic) {
+ next->magic = kPartialRestoreMagic;
+ }
+ }
+
+ lseek64(device_fd, le->source * kSectorSize, SEEK_SET);
+ write(device_fd, &buffer[0], le->size);
+
+ if (index == 0) {
+ fsync(device_fd);
+ }
+}
+
+// Read from the device
+// If we are validating, the read occurs as though the relocations had happened
+std::vector<char> relocatedRead(int device_fd, Relocations const& relocations, bool validating,
+ sector_t sector, uint32_t size, uint32_t block_size) {
+ if (!validating) {
+ std::vector<char> buffer(size);
+ lseek64(device_fd, sector * kSectorSize, SEEK_SET);
+ read(device_fd, &buffer[0], size);
+ return buffer;
+ }
+
+ std::vector<char> buffer(size);
+ for (uint32_t i = 0; i < size; i += block_size, sector += block_size / kSectorSize) {
+ auto relocation = --relocations.upper_bound(sector);
+ lseek64(device_fd, (sector + relocation->second - relocation->first) * kSectorSize,
+ SEEK_SET);
+ read(device_fd, &buffer[i], block_size);
+ }
+
+ return buffer;
+}
+
+} // namespace
+
+Status cp_restoreCheckpoint(const std::string& blockDevice, int restore_limit) {
+ bool validating = true;
+ std::string action = "Validating";
+ int restore_count = 0;
+
+ for (;;) {
+ Relocations relocations;
+ relocations[0] = 0;
+ Status status = Status::ok();
+
+ LOG(INFO) << action << " checkpoint on " << blockDevice;
+ base::unique_fd device_fd(open(blockDevice.c_str(), O_RDWR | O_CLOEXEC));
+ if (device_fd < 0) {
+ PLOG(ERROR) << "Cannot open " << blockDevice;
+ return Status::fromExceptionCode(errno, ("Cannot open " + blockDevice).c_str());
+ }
+
+ log_sector_v1_0 original_ls;
+ read(device_fd, reinterpret_cast<char*>(&original_ls), sizeof(original_ls));
+ if (original_ls.magic == kPartialRestoreMagic) {
+ validating = false;
+ action = "Restoring";
+ } else if (original_ls.magic != kMagic) {
+ LOG(ERROR) << "No magic";
+ return Status::fromExceptionCode(EINVAL, "No magic");
+ }
+
+ LOG(INFO) << action << " " << original_ls.sequence << " log sectors";
+
+ for (int sequence = original_ls.sequence; sequence >= 0 && status.isOk(); sequence--) {
+ auto ls_buffer = relocatedRead(device_fd, relocations, validating, 0,
+ original_ls.block_size, original_ls.block_size);
+ log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]);
+
+ Used_Sectors used_sectors;
+ used_sectors[0] = false;
+
+ if (ls.magic != kMagic && (ls.magic != kPartialRestoreMagic || validating)) {
+ LOG(ERROR) << "No magic!";
+ status = Status::fromExceptionCode(EINVAL, "No magic");
+ break;
+ }
+
+ if (ls.block_size != original_ls.block_size) {
+ LOG(ERROR) << "Block size mismatch!";
+ status = Status::fromExceptionCode(EINVAL, "Block size mismatch");
+ break;
+ }
+
+ if ((int)ls.sequence != sequence) {
+ LOG(ERROR) << "Expecting log sector " << sequence << " but got " << ls.sequence;
+ status = Status::fromExceptionCode(
+ EINVAL, ("Expecting log sector " + std::to_string(sequence) + " but got " +
+ std::to_string(ls.sequence))
+ .c_str());
+ break;
+ }
+
+ LOG(INFO) << action << " from log sector " << ls.sequence;
+ for (log_entry* le =
+ reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]) + ls.count - 1;
+ le >= reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]); --le) {
+ // This is very noisy - limit to DEBUG only
+ LOG(VERBOSE) << action << " " << le->size << " bytes from sector " << le->dest
+ << " to " << le->source << " with checksum " << std::hex
+ << le->checksum;
+
+ auto buffer = relocatedRead(device_fd, relocations, validating, le->dest, le->size,
+ ls.block_size);
+ uint32_t checksum = le->source / (ls.block_size / kSectorSize);
+ for (size_t i = 0; i < le->size; i += ls.block_size) {
+ crc32(&buffer[i], ls.block_size, &checksum);
+ }
+
+ if (le->checksum && checksum != le->checksum) {
+ LOG(ERROR) << "Checksums don't match " << std::hex << checksum;
+ status = Status::fromExceptionCode(EINVAL, "Checksums don't match");
+ break;
+ }
+
+ if (validating) {
+ relocate(relocations, le->source, le->dest, (le->size - 1) / kSectorSize + 1);
+ } else {
+ restoreSector(device_fd, used_sectors, ls_buffer, le, buffer);
+ restore_count++;
+ if (restore_limit && restore_count >= restore_limit) {
+ LOG(WARNING) << "Hit the test limit";
+ status = Status::fromExceptionCode(EAGAIN, "Hit the test limit");
+ break;
+ }
+ }
+ }
+ }
+
+ if (!status.isOk()) {
+ if (!validating) {
+ LOG(ERROR) << "Checkpoint restore failed even though checkpoint validation passed";
+ return status;
+ }
+
+ LOG(WARNING) << "Checkpoint validation failed - attempting to roll forward";
+ auto buffer = relocatedRead(device_fd, relocations, false, original_ls.sector0,
+ original_ls.block_size, original_ls.block_size);
+ lseek64(device_fd, 0, SEEK_SET);
+ write(device_fd, &buffer[0], original_ls.block_size);
+ return Status::ok();
+ }
+
+ if (!validating) break;
+
+ validating = false;
+ action = "Restoring";
+ }
+
+ return Status::ok();
+}
+
+Status cp_markBootAttempt() {
+ std::string oldContent, newContent;
+ int retry = 0;
+ struct stat st;
+ int result = stat(kMetadataCPFile.c_str(), &st);
+
+ // If the file doesn't exist, we aren't managing a checkpoint retry counter
+ if (result != 0) return Status::ok();
+ if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) {
+ PLOG(ERROR) << "Failed to read checkpoint file";
+ return Status::fromExceptionCode(errno, "Failed to read checkpoint file");
+ }
+ std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" "));
+
+ if (!android::base::ParseInt(retryContent, &retry))
+ return Status::fromExceptionCode(EINVAL, "Could not parse retry count");
+ if (retry > 0) {
+ retry--;
+
+ newContent = std::to_string(retry);
+ if (!android::base::WriteStringToFile(newContent, kMetadataCPFile))
+ return Status::fromExceptionCode(errno, "Could not write checkpoint file");
+ }
+ return Status::ok();
+}
+
+} // namespace vold
+} // namespace android
diff --git a/Checkpoint.h b/Checkpoint.h
new file mode 100644
index 0000000..63ead83
--- /dev/null
+++ b/Checkpoint.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _CHECKPOINT_H
+#define _CHECKPOINT_H
+
+#include <binder/Status.h>
+#include <string>
+
+namespace android {
+namespace vold {
+
+android::binder::Status cp_supportsCheckpoint(bool& result);
+
+android::binder::Status cp_supportsBlockCheckpoint(bool& result);
+
+android::binder::Status cp_supportsFileCheckpoint(bool& result);
+
+android::binder::Status cp_startCheckpoint(int retry);
+
+android::binder::Status cp_commitChanges();
+
+void cp_abortChanges(const std::string& message, bool retry);
+
+bool cp_needsRollback();
+
+bool cp_needsCheckpoint();
+
+android::binder::Status cp_prepareCheckpoint();
+
+android::binder::Status cp_restoreCheckpoint(const std::string& mountPoint, int count = 0);
+
+android::binder::Status cp_markBootAttempt();
+
+} // namespace vold
+} // namespace android
+
+#endif
diff --git a/Devmapper.cpp b/Devmapper.cpp
index 2510771..b42467c 100644
--- a/Devmapper.cpp
+++ b/Devmapper.cpp
@@ -16,23 +16,22 @@
#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
+#include <errno.h>
+#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <errno.h>
#include <string.h>
-#include <stdlib.h>
+#include <unistd.h>
-#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
+#include <sys/types.h>
#include <linux/kdev_t.h>
#include <android-base/logging.h>
-#include <android-base/strings.h>
#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include <utils/Trace.h>
#include "Devmapper.h"
@@ -43,8 +42,7 @@
static const char* kVoldPrefix = "vold:";
-void Devmapper::ioctlInit(struct dm_ioctl *io, size_t dataSize,
- const char *name, unsigned flags) {
+void Devmapper::ioctlInit(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
memset(io, 0, dataSize);
io->data_size = dataSize;
io->data_start = sizeof(struct dm_ioctl);
@@ -54,17 +52,16 @@
io->flags = flags;
if (name) {
size_t ret = strlcpy(io->name, name, sizeof(io->name));
- if (ret >= sizeof(io->name))
- abort();
+ if (ret >= sizeof(io->name)) abort();
}
}
-int Devmapper::create(const char *name_raw, const char *loopFile, const char *key,
- unsigned long numSectors, char *ubuffer, size_t len) {
+int Devmapper::create(const char* name_raw, const char* loopFile, const char* key,
+ unsigned long numSectors, char* ubuffer, size_t len) {
auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw);
const char* name = name_string.c_str();
- char *buffer = (char *) malloc(DEVMAPPER_BUFFER_SIZE);
+ char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
if (!buffer) {
PLOG(ERROR) << "Failed malloc";
return -1;
@@ -77,8 +74,8 @@
return -1;
}
- struct dm_ioctl *io = (struct dm_ioctl *) buffer;
-
+ struct dm_ioctl* io = (struct dm_ioctl*)buffer;
+
// Create the DM device
ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
@@ -92,11 +89,11 @@
// Set the legacy geometry
ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
- char *geoParams = buffer + sizeof(struct dm_ioctl);
+ char* geoParams = buffer + sizeof(struct dm_ioctl);
// bps=512 spc=8 res=32 nft=2 sec=8190 mid=0xf0 spt=63 hds=64 hid=0 bspf=8 rdcl=2 infs=1 bkbs=2
strlcpy(geoParams, "0 64 63 0", DEVMAPPER_BUFFER_SIZE - sizeof(struct dm_ioctl));
geoParams += strlen(geoParams) + 1;
- geoParams = (char *) _align(geoParams, 8);
+ geoParams = (char*)_align(geoParams, 8);
if (ioctl(fd, DM_DEV_SET_GEOMETRY, io)) {
PLOG(ERROR) << "Failed DM_DEV_SET_GEOMETRY";
free(buffer);
@@ -117,8 +114,8 @@
snprintf(ubuffer, len, "/dev/block/dm-%u", minor);
// Load the table
- struct dm_target_spec *tgt;
- tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
+ struct dm_target_spec* tgt;
+ tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, DM_STATUS_TABLE_FLAG);
io->target_count = 1;
@@ -129,12 +126,12 @@
strlcpy(tgt->target_type, "crypt", sizeof(tgt->target_type));
- char *cryptParams = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
+ char* cryptParams = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
snprintf(cryptParams,
- DEVMAPPER_BUFFER_SIZE - (sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec)),
- "twofish %s 0 %s 0", key, loopFile);
+ DEVMAPPER_BUFFER_SIZE - (sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec)),
+ "twofish %s 0 %s 0", key, loopFile);
cryptParams += strlen(cryptParams) + 1;
- cryptParams = (char *) _align(cryptParams, 8);
+ cryptParams = (char*)_align(cryptParams, 8);
tgt->next = cryptParams - buffer;
if (ioctl(fd, DM_TABLE_LOAD, io)) {
@@ -160,11 +157,11 @@
return 0;
}
-int Devmapper::destroy(const char *name_raw) {
+int Devmapper::destroy(const char* name_raw) {
auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw);
const char* name = name_string.c_str();
- char *buffer = (char *) malloc(DEVMAPPER_BUFFER_SIZE);
+ char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
if (!buffer) {
PLOG(ERROR) << "Failed malloc";
return -1;
@@ -177,8 +174,8 @@
return -1;
}
- struct dm_ioctl *io = (struct dm_ioctl *) buffer;
-
+ struct dm_ioctl* io = (struct dm_ioctl*)buffer;
+
// Create the DM device
ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
@@ -198,14 +195,14 @@
int Devmapper::destroyAll() {
ATRACE_NAME("Devmapper::destroyAll");
- char *buffer = (char *) malloc(1024 * 64);
+ char* buffer = (char*)malloc(1024 * 64);
if (!buffer) {
PLOG(ERROR) << "Failed malloc";
return -1;
}
memset(buffer, 0, (1024 * 64));
- char *buffer2 = (char *) malloc(DEVMAPPER_BUFFER_SIZE);
+ char* buffer2 = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
if (!buffer2) {
PLOG(ERROR) << "Failed malloc";
free(buffer);
@@ -220,7 +217,7 @@
return -1;
}
- struct dm_ioctl *io = (struct dm_ioctl *) buffer;
+ struct dm_ioctl* io = (struct dm_ioctl*)buffer;
ioctlInit(io, (1024 * 64), NULL, 0);
if (ioctl(fd, DM_LIST_DEVICES, io)) {
@@ -231,7 +228,7 @@
return -1;
}
- struct dm_name_list *n = (struct dm_name_list *) (((char *) buffer) + io->data_start);
+ struct dm_name_list* n = (struct dm_name_list*)(((char*)buffer) + io->data_start);
if (!n->dev) {
free(buffer);
free(buffer2);
@@ -241,13 +238,13 @@
unsigned nxt = 0;
do {
- n = (struct dm_name_list *) (((char *) n) + nxt);
+ n = (struct dm_name_list*)(((char*)n) + nxt);
auto name = std::string(n->name);
if (android::base::StartsWith(name, kVoldPrefix)) {
LOG(DEBUG) << "Tearing down stale dm device named " << name;
memset(buffer2, 0, DEVMAPPER_BUFFER_SIZE);
- struct dm_ioctl *io2 = (struct dm_ioctl *) buffer2;
+ struct dm_ioctl* io2 = (struct dm_ioctl*)buffer2;
ioctlInit(io2, DEVMAPPER_BUFFER_SIZE, n->name, 0);
if (ioctl(fd, DM_DEV_REMOVE, io2)) {
if (errno != ENXIO) {
@@ -255,7 +252,7 @@
}
}
} else {
- LOG(VERBOSE) << "Found unmanaged dm device named " << name;
+ LOG(DEBUG) << "Found unmanaged dm device named " << name;
}
nxt = n->next;
} while (nxt);
@@ -266,9 +263,8 @@
return 0;
}
-void *Devmapper::_align(void *ptr, unsigned int a)
-{
- unsigned long agn = --a;
+void* Devmapper::_align(void* ptr, unsigned int a) {
+ unsigned long agn = --a;
- return (void *) (((unsigned long) ptr + agn) & ~agn);
+ return (void*)(((unsigned long)ptr + agn) & ~agn);
}
diff --git a/Devmapper.h b/Devmapper.h
index 7bb9786..b1f6dfa 100644
--- a/Devmapper.h
+++ b/Devmapper.h
@@ -17,20 +17,19 @@
#ifndef _DEVMAPPER_H
#define _DEVMAPPER_H
-#include <unistd.h>
#include <linux/dm-ioctl.h>
+#include <unistd.h>
class Devmapper {
-public:
- static int create(const char *name, const char *loopFile, const char *key,
- unsigned long numSectors, char *buffer, size_t len);
- static int destroy(const char *name);
+ public:
+ static int create(const char* name, const char* loopFile, const char* key,
+ unsigned long numSectors, char* buffer, size_t len);
+ static int destroy(const char* name);
static int destroyAll();
-private:
- static void *_align(void *ptr, unsigned int a);
- static void ioctlInit(struct dm_ioctl *io, size_t data_size,
- const char *name, unsigned flags);
+ private:
+ static void* _align(void* ptr, unsigned int a);
+ static void ioctlInit(struct dm_ioctl* io, size_t data_size, const char* name, unsigned flags);
};
#endif
diff --git a/EncryptInplace.cpp b/EncryptInplace.cpp
index 6462dbf..f55932d 100644
--- a/EncryptInplace.cpp
+++ b/EncryptInplace.cpp
@@ -16,16 +16,16 @@
#include "EncryptInplace.h"
-#include <stdio.h>
-#include <stdint.h>
-#include <inttypes.h>
-#include <time.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
#include <ext4_utils/ext4.h>
#include <ext4_utils/ext4_utils.h>
#include <f2fs_sparseblock.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <time.h>
#include <algorithm>
@@ -36,13 +36,11 @@
#include "cryptfs.h"
// FIXME horrible cut-and-paste code
-static inline int unix_read(int fd, void* buff, int len)
-{
+static inline int unix_read(int fd, void* buff, int len) {
return TEMP_FAILURE_RETRY(read(fd, buff, len));
}
-static inline int unix_write(int fd, const void* buff, int len)
-{
+static inline int unix_write(int fd, const void* buff, int len) {
return TEMP_FAILURE_RETRY(write(fd, buff, len));
}
@@ -57,15 +55,14 @@
#define BLOCKS_AT_A_TIME 1024
#endif
-struct encryptGroupsData
-{
+struct encryptGroupsData {
int realfd;
int cryptofd;
off64_t numblocks;
off64_t one_pct, cur_pct, new_pct;
off64_t blocks_already_done, tot_numblocks;
off64_t used_blocks_already_done, tot_used_blocks;
- char* real_blkdev, * crypto_blkdev;
+ char *real_blkdev, *crypto_blkdev;
int count;
off64_t offset;
char* buffer;
@@ -76,8 +73,7 @@
bool set_progress_properties;
};
-static void update_progress(struct encryptGroupsData* data, int is_used)
-{
+static void update_progress(struct encryptGroupsData* data, int is_used) {
data->blocks_already_done++;
if (is_used) {
@@ -104,16 +100,14 @@
LOG(WARNING) << "Error getting time";
} else {
double elapsed_time = difftime(time_now.tv_sec, data->time_started);
- off64_t remaining_blocks = data->tot_used_blocks
- - data->used_blocks_already_done;
- int remaining_time = (int)(elapsed_time * remaining_blocks
- / data->used_blocks_already_done);
+ off64_t remaining_blocks = data->tot_used_blocks - data->used_blocks_already_done;
+ int remaining_time =
+ (int)(elapsed_time * remaining_blocks / data->used_blocks_already_done);
// Change time only if not yet set, lower, or a lot higher for
// best user experience
- if (data->remaining_time == -1
- || remaining_time < data->remaining_time
- || remaining_time > data->remaining_time + 60) {
+ if (data->remaining_time == -1 || remaining_time < data->remaining_time ||
+ remaining_time > data->remaining_time + 60) {
char buf[8];
snprintf(buf, sizeof(buf), "%d", remaining_time);
android::base::SetProperty("vold.encrypt_time_remaining", buf);
@@ -123,8 +117,7 @@
}
}
-static void log_progress(struct encryptGroupsData const* data, bool completed)
-{
+static void log_progress(struct encryptGroupsData const* data, bool completed) {
// Precondition - if completed data = 0 else data != 0
// Track progress so we can skip logging blocks
@@ -147,13 +140,12 @@
}
}
-static int flush_outstanding_data(struct encryptGroupsData* data)
-{
+static int flush_outstanding_data(struct encryptGroupsData* data) {
if (data->count == 0) {
return 0;
}
- LOG(VERBOSE) << "Copying " << data->count << " blocks at offset " << data->offset;
+ LOG(DEBUG) << "Copying " << data->count << " blocks at offset " << data->offset;
if (pread64(data->realfd, data->buffer, info.block_size * data->count, data->offset) <= 0) {
LOG(ERROR) << "Error reading real_blkdev " << data->real_blkdev << " for inplace encrypt";
@@ -165,30 +157,29 @@
<< " for inplace encrypt";
return -1;
} else {
- log_progress(data, false);
+ log_progress(data, false);
}
data->count = 0;
- data->last_written_sector = (data->offset + data->count)
- / info.block_size * CRYPT_SECTOR_SIZE - 1;
+ data->last_written_sector =
+ (data->offset + data->count) / info.block_size * CRYPT_SECTOR_SIZE - 1;
return 0;
}
-static int encrypt_groups(struct encryptGroupsData* data)
-{
+static int encrypt_groups(struct encryptGroupsData* data) {
unsigned int i;
- u8 *block_bitmap = 0;
+ u8* block_bitmap = 0;
unsigned int block;
off64_t ret;
int rc = -1;
- data->buffer = (char*) malloc(info.block_size * BLOCKS_AT_A_TIME);
+ data->buffer = (char*)malloc(info.block_size * BLOCKS_AT_A_TIME);
if (!data->buffer) {
LOG(ERROR) << "Failed to allocate crypto buffer";
goto errout;
}
- block_bitmap = (u8*) malloc(info.block_size);
+ block_bitmap = (u8*)malloc(info.block_size);
if (!block_bitmap) {
LOG(ERROR) << "failed to allocate block bitmap";
goto errout;
@@ -198,11 +189,9 @@
LOG(INFO) << "Encrypting group " << i;
u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
- u32 block_count = std::min(info.blocks_per_group,
- (u32)(aux_info.len_blocks - first_block));
+ u32 block_count = std::min(info.blocks_per_group, (u32)(aux_info.len_blocks - first_block));
- off64_t offset = (u64)info.block_size
- * aux_info.bg_desc[i].bg_block_bitmap;
+ off64_t offset = (u64)info.block_size * aux_info.bg_desc[i].bg_block_bitmap;
ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
if (ret != (int)info.block_size) {
@@ -215,8 +204,9 @@
data->count = 0;
for (block = 0; block < block_count; block++) {
- int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
- 0 : bitmap_get_bit(block_bitmap, block);
+ int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT)
+ ? 0
+ : bitmap_get_bit(block_bitmap, block);
update_progress(data, used);
if (used) {
if (data->count == 0) {
@@ -232,8 +222,8 @@
offset += info.block_size;
/* Write data if we are aligned or buffer size reached */
- if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
- || data->count == BLOCKS_AT_A_TIME) {
+ if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0 ||
+ data->count == BLOCKS_AT_A_TIME) {
if (flush_outstanding_data(data)) {
goto errout;
}
@@ -260,7 +250,7 @@
bool set_progress_properties) {
u32 i;
struct encryptGroupsData data;
- int rc; // Can't initialize without causing warning -Wclobbered
+ int rc; // Can't initialize without causing warning -Wclobbered
int retries = RETRY_MOUNT_ATTEMPTS;
struct timespec time_started = {0};
@@ -275,7 +265,7 @@
data.set_progress_properties = set_progress_properties;
LOG(DEBUG) << "Opening" << real_blkdev;
- if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
+ if ((data.realfd = open(real_blkdev, O_RDWR | O_CLOEXEC)) < 0) {
PLOG(ERROR) << "Error opening real_blkdev " << real_blkdev << " for inplace encrypt";
rc = -1;
goto errout;
@@ -283,7 +273,7 @@
LOG(DEBUG) << "Opening" << crypto_blkdev;
// Wait until the block device appears. Re-use the mount retry values since it is reasonable.
- while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+ while ((data.cryptofd = open(crypto_blkdev, O_WRONLY | O_CLOEXEC)) < 0) {
if (--retries) {
PLOG(ERROR) << "Error opening crypto_blkdev " << crypto_blkdev
<< " for ext4 inplace encrypt, retrying";
@@ -296,7 +286,7 @@
}
}
- if (setjmp(setjmp_env)) { // NOLINT
+ if (setjmp(setjmp_env)) { // NOLINT
LOG(ERROR) << "Reading ext4 extent caused an exception";
rc = -1;
goto errout;
@@ -316,7 +306,7 @@
data.tot_used_blocks = data.numblocks;
for (i = 0; i < aux_info.groups; ++i) {
- data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
+ data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
}
data.one_pct = data.tot_used_blocks / 100;
@@ -345,8 +335,7 @@
return rc;
}
-static void log_progress_f2fs(u64 block, bool completed)
-{
+static void log_progress_f2fs(u64 block, bool completed) {
// Precondition - if completed data = 0 else data != 0
// Track progress so we can skip logging blocks
@@ -369,9 +358,8 @@
}
}
-static int encrypt_one_block_f2fs(u64 pos, void *data)
-{
- struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
+static int encrypt_one_block_f2fs(u64 pos, void* data) {
+ struct encryptGroupsData* priv_dat = (struct encryptGroupsData*)data;
priv_dat->blocks_already_done = pos - 1;
update_progress(priv_dat, 1);
@@ -400,7 +388,7 @@
off64_t previously_encrypted_upto,
bool set_progress_properties) {
struct encryptGroupsData data;
- struct f2fs_info *f2fs_info = NULL;
+ struct f2fs_info* f2fs_info = NULL;
int rc = ENABLE_INPLACE_ERR_OTHER;
if (previously_encrypted_upto > *size_already_done) {
LOG(DEBUG) << "Not fast encrypting since resuming part way through";
@@ -412,11 +400,11 @@
data.set_progress_properties = set_progress_properties;
data.realfd = -1;
data.cryptofd = -1;
- if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
+ if ((data.realfd = open64(real_blkdev, O_RDWR | O_CLOEXEC)) < 0) {
PLOG(ERROR) << "Error opening real_blkdev " << real_blkdev << " for f2fs inplace encrypt";
goto errout;
}
- if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+ if ((data.cryptofd = open64(crypto_blkdev, O_WRONLY | O_CLOEXEC)) < 0) {
PLOG(ERROR) << "Error opening crypto_blkdev " << crypto_blkdev
<< " for f2fs inplace encrypt";
rc = ENABLE_INPLACE_ERR_DEV;
@@ -424,8 +412,7 @@
}
f2fs_info = generate_f2fs_info(data.realfd);
- if (!f2fs_info)
- goto errout;
+ if (!f2fs_info) goto errout;
data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
@@ -438,7 +425,7 @@
data.time_started = time(NULL);
data.remaining_time = -1;
- data.buffer = (char*) malloc(f2fs_info->block_size);
+ data.buffer = (char*)malloc(f2fs_info->block_size);
if (!data.buffer) {
LOG(ERROR) << "Failed to allocate crypto buffer";
goto errout;
@@ -475,18 +462,18 @@
off64_t previously_encrypted_upto,
bool set_progress_properties) {
int realfd, cryptofd;
- char *buf[CRYPT_INPLACE_BUFSIZE];
+ char* buf[CRYPT_INPLACE_BUFSIZE];
int rc = ENABLE_INPLACE_ERR_OTHER;
off64_t numblocks, i, remainder;
off64_t one_pct, cur_pct, new_pct;
off64_t blocks_already_done, tot_numblocks;
- if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
+ if ((realfd = open(real_blkdev, O_RDONLY | O_CLOEXEC)) < 0) {
PLOG(ERROR) << "Error opening real_blkdev " << real_blkdev << " for inplace encrypt";
return ENABLE_INPLACE_ERR_OTHER;
}
- if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+ if ((cryptofd = open(crypto_blkdev, O_WRONLY | O_CLOEXEC)) < 0) {
PLOG(ERROR) << "Error opening crypto_blkdev " << crypto_blkdev << " for inplace encrypt";
close(realfd);
return ENABLE_INPLACE_ERR_DEV;
@@ -516,7 +503,7 @@
goto errout;
}
- for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
+ for (; i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
PLOG(ERROR) << "Error reading initial sectors from real_blkdev " << real_blkdev
<< " for inplace encrypt";
@@ -534,14 +521,14 @@
one_pct = tot_numblocks / 100;
cur_pct = 0;
/* process the majority of the filesystem in blocks */
- for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
+ for (i /= CRYPT_SECTORS_PER_BUFSIZE; i < numblocks; i++) {
new_pct = (i + blocks_already_done) / one_pct;
if (set_progress_properties && new_pct > cur_pct) {
- char buf[8];
+ char property_buf[8];
cur_pct = new_pct;
- snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
- android::base::SetProperty("vold.encrypt_progress", buf);
+ snprintf(property_buf, sizeof(property_buf), "%" PRId64, cur_pct);
+ android::base::SetProperty("vold.encrypt_progress", property_buf);
}
if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
PLOG(ERROR) << "Error reading real_blkdev " << real_blkdev << " for inplace encrypt";
@@ -557,7 +544,7 @@
}
/* Do any remaining sectors */
- for (i=0; i<remainder; i++) {
+ for (i = 0; i < remainder; i++) {
if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
LOG(ERROR) << "Error reading final sectors from real_blkdev " << real_blkdev
<< " for inplace encrypt";
@@ -626,9 +613,8 @@
LOG(DEBUG) << "cryptfs_enable_inplace_full()=" << rc_full;
/* Hack for b/17898962, the following is the symptom... */
- if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
- && rc_f2fs == ENABLE_INPLACE_ERR_DEV
- && rc_full == ENABLE_INPLACE_ERR_DEV) {
+ if (rc_ext4 == ENABLE_INPLACE_ERR_DEV && rc_f2fs == ENABLE_INPLACE_ERR_DEV &&
+ rc_full == ENABLE_INPLACE_ERR_DEV) {
LOG(DEBUG) << "ENABLE_INPLACE_ERR_DEV";
return ENABLE_INPLACE_ERR_DEV;
}
diff --git a/FileDeviceUtils.cpp b/FileDeviceUtils.cpp
index bc9f4bd..c745b54 100644
--- a/FileDeviceUtils.cpp
+++ b/FileDeviceUtils.cpp
@@ -16,15 +16,15 @@
#include "FileDeviceUtils.h"
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/fiemap.h>
+#include <linux/fs.h>
+#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
-#include <errno.h>
-#include <sys/types.h>
#include <sys/stat.h>
-#include <fcntl.h>
-#include <linux/fs.h>
-#include <linux/fiemap.h>
-#include <mntent.h>
+#include <sys/types.h>
#include <android-base/file.h>
#include <android-base/logging.h>
@@ -40,38 +40,32 @@
namespace vold {
// Given a file path, look for the corresponding block device in /proc/mount
-std::string BlockDeviceForPath(const std::string &path)
-{
- std::unique_ptr<FILE, int(*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
+std::string BlockDeviceForPath(const std::string& path) {
+ std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
if (!mnts) {
PLOG(ERROR) << "Unable to open /proc/mounts";
return "";
}
std::string result;
size_t best_length = 0;
- struct mntent *mnt; // getmntent returns a thread local, so it's safe.
+ struct mntent* mnt; // getmntent returns a thread local, so it's safe.
while ((mnt = getmntent(mnts.get())) != nullptr) {
auto l = strlen(mnt->mnt_dir);
- if (l > best_length &&
- path.size() > l &&
- path[l] == '/' &&
+ if (l > best_length && path.size() > l && path[l] == '/' &&
path.compare(0, l, mnt->mnt_dir) == 0) {
- result = mnt->mnt_fsname;
- best_length = l;
+ result = mnt->mnt_fsname;
+ best_length = l;
}
}
if (result.empty()) {
- LOG(ERROR) <<"Didn't find a mountpoint to match path " << path;
+ LOG(ERROR) << "Didn't find a mountpoint to match path " << path;
return "";
}
- LOG(DEBUG) << "For path " << path << " block device is " << result;
return result;
}
-std::unique_ptr<struct fiemap> PathFiemap(const std::string &path, uint32_t extent_count)
-{
- android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(
- path.c_str(), O_RDONLY | O_CLOEXEC, 0)));
+std::unique_ptr<struct fiemap> PathFiemap(const std::string& path, uint32_t extent_count) {
+ android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC, 0)));
if (fd == -1) {
if (errno == ENOENT) {
PLOG(DEBUG) << "Unable to open " << path;
@@ -88,7 +82,7 @@
auto mapped = fiemap->fm_mapped_extents;
if (mapped < 1 || mapped > extent_count) {
LOG(ERROR) << "Extent count not in bounds 1 <= " << mapped << " <= " << extent_count
- << " in " << path;
+ << " in " << path;
return nullptr;
}
return fiemap;
@@ -99,10 +93,9 @@
namespace {
-std::unique_ptr<struct fiemap> alloc_fiemap(uint32_t extent_count)
-{
+std::unique_ptr<struct fiemap> alloc_fiemap(uint32_t extent_count) {
size_t allocsize = offsetof(struct fiemap, fm_extents[extent_count]);
- std::unique_ptr<struct fiemap> res(new (::operator new (allocsize)) struct fiemap);
+ std::unique_ptr<struct fiemap> res(new (::operator new(allocsize)) struct fiemap);
memset(res.get(), 0, allocsize);
res->fm_start = 0;
res->fm_length = UINT64_MAX;
@@ -112,4 +105,4 @@
return res;
}
-}
+} // namespace
diff --git a/FileDeviceUtils.h b/FileDeviceUtils.h
index 4c1d49a..4428cef 100644
--- a/FileDeviceUtils.h
+++ b/FileDeviceUtils.h
@@ -17,17 +17,17 @@
#ifndef ANDROID_VOLD_FILEDEVICEUTILS_H
#define ANDROID_VOLD_FILEDEVICEUTILS_H
-#include <string>
#include <linux/fiemap.h>
+#include <string>
namespace android {
namespace vold {
// Given a file path, look for the corresponding block device in /proc/mount
-std::string BlockDeviceForPath(const std::string &path);
+std::string BlockDeviceForPath(const std::string& path);
// Read the file's FIEMAP
-std::unique_ptr<struct fiemap> PathFiemap(const std::string &path, uint32_t extent_count);
+std::unique_ptr<struct fiemap> PathFiemap(const std::string& path, uint32_t extent_count);
} // namespace vold
} // namespace android
diff --git a/Ext4Crypt.cpp b/FsCrypt.cpp
similarity index 87%
rename from Ext4Crypt.cpp
rename to FsCrypt.cpp
index 68439c0..b7d3928 100644
--- a/Ext4Crypt.cpp
+++ b/FsCrypt.cpp
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include "Ext4Crypt.h"
+#include "FsCrypt.h"
#include "KeyStorage.h"
#include "KeyUtil.h"
@@ -31,12 +31,12 @@
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
-#include <unistd.h>
#include <limits.h>
#include <selinux/android.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
+#include <unistd.h>
#include <private/android_filesystem_config.h>
@@ -50,18 +50,20 @@
#include <cutils/fs.h>
#include <cutils/properties.h>
-#include <ext4_utils/ext4_crypt.h>
+#include <fscrypt/fscrypt.h>
#include <keyutils.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
using android::base::StringPrintf;
-using android::base::WriteStringToFile;
+using android::fs_mgr::GetEntryForMountPoint;
using android::vold::kEmptyAuthentication;
using android::vold::KeyBuffer;
+using android::vold::writeStringToFile;
namespace {
@@ -71,7 +73,7 @@
std::string key_raw_ref;
};
-const std::string device_key_dir = std::string() + DATA_MNT_POINT + e4crypt_unencrypted_folder;
+const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
const std::string device_key_path = device_key_dir + "/key";
const std::string device_key_temp = device_key_dir + "/temp";
@@ -93,9 +95,9 @@
// TODO abolish this map, per b/26948053
std::map<userid_t, KeyBuffer> s_ce_keys;
-}
+} // namespace
-static bool e4crypt_is_emulated() {
+static bool fscrypt_is_emulated() {
return property_get_bool("persist.sys.emulate_fbe", false);
}
@@ -145,8 +147,7 @@
}
static bool get_ce_key_new_path(const std::string& directory_path,
- const std::vector<std::string>& paths,
- std::string *ce_key_path) {
+ const std::vector<std::string>& paths, std::string* ce_key_path) {
if (paths.empty()) {
*ce_key_path = get_ce_key_current_path(directory_path);
return true;
@@ -163,9 +164,9 @@
// Discard all keys but the named one; rename it to canonical name.
// No point in acting on errors in this; ignore them.
-static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
+static void fixate_user_ce_key(const std::string& directory_path, const std::string& to_fix,
const std::vector<std::string>& paths) {
- for (auto const other_path: paths) {
+ for (auto const other_path : paths) {
if (other_path != to_fix) {
android::vold::destroyKey(other_path);
}
@@ -175,6 +176,7 @@
LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
+ return;
}
}
android::vold::FsyncDirectory(directory_path);
@@ -182,10 +184,10 @@
static bool read_and_fixate_user_ce_key(userid_t user_id,
const android::vold::KeyAuthentication& auth,
- KeyBuffer *ce_key) {
+ KeyBuffer* ce_key) {
auto const directory_path = get_ce_key_directory_path(user_id);
auto const paths = get_ce_key_paths(directory_path);
- for (auto const ce_key_path: paths) {
+ for (auto const ce_key_path : paths) {
LOG(DEBUG) << "Trying user CE key " << ce_key_path;
if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
LOG(DEBUG) << "Successfully retrieved key";
@@ -243,12 +245,14 @@
auto const paths = get_ce_key_paths(directory_path);
std::string ce_key_path;
if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
- if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp,
- kEmptyAuthentication, ce_key)) return false;
+ if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, kEmptyAuthentication,
+ ce_key))
+ return false;
fixate_user_ce_key(directory_path, ce_key_path, paths);
// Write DE key second; once this is written, all is good.
if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
- kEmptyAuthentication, de_key)) return false;
+ kEmptyAuthentication, de_key))
+ return false;
}
std::string de_raw_ref;
if (!android::vold::installKey(de_key, &de_raw_ref)) return false;
@@ -265,7 +269,7 @@
std::string* raw_ref) {
auto refi = key_map.find(user_id);
if (refi == key_map.end()) {
- LOG(ERROR) << "Cannot find key for " << user_id;
+ LOG(DEBUG) << "Cannot find key for " << user_id;
return false;
}
*raw_ref = refi->second;
@@ -273,16 +277,16 @@
}
static void get_data_file_encryption_modes(PolicyKeyRef* key_ref) {
- struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
- char const* contents_mode;
- char const* filenames_mode;
- fs_mgr_get_file_encryption_modes(rec, &contents_mode, &filenames_mode);
- key_ref->contents_mode = contents_mode;
- key_ref->filenames_mode = filenames_mode;
+ auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
+ if (entry == nullptr) {
+ return;
+ }
+ key_ref->contents_mode = entry->file_contents_mode;
+ key_ref->filenames_mode = entry->file_names_mode;
}
static bool ensure_policy(const PolicyKeyRef& key_ref, const std::string& path) {
- return e4crypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
+ return fscrypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
key_ref.key_raw_ref.size(), key_ref.contents_mode.c_str(),
key_ref.filenames_mode.c_str()) == 0;
}
@@ -326,13 +330,13 @@
LOG(DEBUG) << "Installed de key for user " << user_id;
}
}
- // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
+ // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
// correct policy set on them, and that no rogue ones exist.
return true;
}
-bool e4crypt_initialize_global_de() {
- LOG(INFO) << "e4crypt_initialize_global_de";
+bool fscrypt_initialize_global_de() {
+ LOG(INFO) << "fscrypt_initialize_global_de";
if (s_global_de_initialized) {
LOG(INFO) << "Already initialized";
@@ -346,26 +350,22 @@
get_data_file_encryption_modes(&device_ref);
std::string modestring = device_ref.contents_mode + ":" + device_ref.filenames_mode;
- std::string mode_filename = std::string("/data") + e4crypt_key_mode;
- if (!android::base::WriteStringToFile(modestring, mode_filename)) {
- PLOG(ERROR) << "Cannot save type";
- return false;
- }
+ std::string mode_filename = std::string("/data") + fscrypt_key_mode;
+ if (!android::vold::writeStringToFile(modestring, mode_filename)) return false;
- std::string ref_filename = std::string("/data") + e4crypt_key_ref;
- if (!android::base::WriteStringToFile(device_ref.key_raw_ref, ref_filename)) {
- PLOG(ERROR) << "Cannot save key reference to:" << ref_filename;
- return false;
- }
+ std::string ref_filename = std::string("/data") + fscrypt_key_ref;
+ if (!android::vold::writeStringToFile(device_ref.key_raw_ref, ref_filename)) return false;
+
LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
+ if (!android::vold::FsyncDirectory(device_key_dir)) return false;
s_global_de_initialized = true;
return true;
}
-bool e4crypt_init_user0() {
- LOG(DEBUG) << "e4crypt_init_user0";
- if (e4crypt_is_native()) {
+bool fscrypt_init_user0() {
+ LOG(DEBUG) << "fscrypt_init_user0";
+ if (fscrypt_is_native()) {
if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
@@ -379,28 +379,28 @@
// We can only safely prepare DE storage here, since CE keys are probably
// entangled with user credentials. The framework will always prepare CE
// storage once CE keys are installed.
- if (!e4crypt_prepare_user_storage("", 0, 0, android::os::IVold::STORAGE_FLAG_DE)) {
+ if (!fscrypt_prepare_user_storage("", 0, 0, android::os::IVold::STORAGE_FLAG_DE)) {
LOG(ERROR) << "Failed to prepare user 0 storage";
return false;
}
// If this is a non-FBE device that recently left an emulated mode,
// restore user data directories to known-good state.
- if (!e4crypt_is_native() && !e4crypt_is_emulated()) {
- e4crypt_unlock_user_key(0, 0, "!", "!");
+ if (!fscrypt_is_native() && !fscrypt_is_emulated()) {
+ fscrypt_unlock_user_key(0, 0, "!", "!");
}
return true;
}
-bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
- LOG(DEBUG) << "e4crypt_vold_create_user_key for " << user_id << " serial " << serial;
- if (!e4crypt_is_native()) {
+bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
+ LOG(DEBUG) << "fscrypt_vold_create_user_key for " << user_id << " serial " << serial;
+ if (!fscrypt_is_native()) {
return true;
}
// FIXME test for existence of key that is not loaded yet
if (s_ce_key_raw_refs.count(user_id) != 0) {
- LOG(ERROR) << "Already exists, can't e4crypt_vold_create_user_key for " << user_id
+ LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
<< " serial " << serial;
// FIXME should we fail the command?
return true;
@@ -415,7 +415,7 @@
// Clean any dirty pages (otherwise they won't be dropped).
sync();
// Drop inode and page caches.
- if (!WriteStringToFile("3", "/proc/sys/vm/drop_caches")) {
+ if (!writeStringToFile("3", "/proc/sys/vm/drop_caches")) {
PLOG(ERROR) << "Failed to drop caches during key eviction";
}
}
@@ -433,22 +433,22 @@
return success;
}
-bool e4crypt_destroy_user_key(userid_t user_id) {
- LOG(DEBUG) << "e4crypt_destroy_user_key(" << user_id << ")";
- if (!e4crypt_is_native()) {
+bool fscrypt_destroy_user_key(userid_t user_id) {
+ LOG(DEBUG) << "fscrypt_destroy_user_key(" << user_id << ")";
+ if (!fscrypt_is_native()) {
return true;
}
bool success = true;
std::string raw_ref;
success &= evict_ce_key(user_id);
- success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)
- && android::vold::evictKey(raw_ref);
+ success &=
+ lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && android::vold::evictKey(raw_ref);
s_de_key_raw_refs.erase(user_id);
auto it = s_ephemeral_users.find(user_id);
if (it != s_ephemeral_users.end()) {
s_ephemeral_users.erase(it);
} else {
- for (auto const path: get_ce_key_paths(get_ce_key_directory_path(user_id))) {
+ for (auto const path : get_ce_key_paths(get_ce_key_directory_path(user_id))) {
success &= android::vold::destroyKey(path);
}
auto de_key_path = get_de_key_path(user_id);
@@ -479,13 +479,13 @@
if (chmod(path.c_str(), mode) != 0) {
PLOG(ERROR) << "Failed to chmod " << path;
// FIXME temporary workaround for b/26713622
- if (e4crypt_is_emulated()) return false;
+ if (fscrypt_is_emulated()) return false;
}
#if EMULATED_USES_SELINUX
if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_FORCE) != 0) {
PLOG(WARNING) << "Failed to restorecon " << path;
// FIXME temporary workaround for b/26713622
- if (e4crypt_is_emulated()) return false;
+ if (fscrypt_is_emulated()) return false;
}
#endif
return true;
@@ -548,23 +548,23 @@
return android::vold::destroyKey(path);
}
-bool e4crypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
+bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
const std::string& secret_hex) {
- LOG(DEBUG) << "e4crypt_add_user_key_auth " << user_id << " serial=" << serial
+ LOG(DEBUG) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial
<< " token_present=" << (token_hex != "!");
- if (!e4crypt_is_native()) return true;
+ if (!fscrypt_is_native()) return true;
if (s_ephemeral_users.count(user_id) != 0) return true;
std::string token, secret;
if (!parse_hex(token_hex, &token)) return false;
if (!parse_hex(secret_hex, &secret)) return false;
- auto auth = secret.empty() ? kEmptyAuthentication
- : android::vold::KeyAuthentication(token, secret);
+ auto auth =
+ secret.empty() ? kEmptyAuthentication : android::vold::KeyAuthentication(token, secret);
auto it = s_ce_keys.find(user_id);
if (it == s_ce_keys.end()) {
LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
return false;
}
- const auto &ce_key = it->second;
+ const auto& ce_key = it->second;
auto const directory_path = get_ce_key_directory_path(user_id);
auto const paths = get_ce_key_paths(directory_path);
std::string ce_key_path;
@@ -574,9 +574,9 @@
return true;
}
-bool e4crypt_fixate_newest_user_key_auth(userid_t user_id) {
- LOG(DEBUG) << "e4crypt_fixate_newest_user_key_auth " << user_id;
- if (!e4crypt_is_native()) return true;
+bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
+ LOG(DEBUG) << "fscrypt_fixate_newest_user_key_auth " << user_id;
+ if (!fscrypt_is_native()) return true;
if (s_ephemeral_users.count(user_id) != 0) return true;
auto const directory_path = get_ce_key_directory_path(user_id);
auto const paths = get_ce_key_paths(directory_path);
@@ -589,11 +589,11 @@
}
// TODO: rename to 'install' for consistency, and take flags to know which keys to install
-bool e4crypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
+bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
const std::string& secret_hex) {
- LOG(DEBUG) << "e4crypt_unlock_user_key " << user_id << " serial=" << serial
+ LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
<< " token_present=" << (token_hex != "!");
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
if (s_ce_key_raw_refs.count(user_id) != 0) {
LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
return true;
@@ -622,11 +622,11 @@
}
// TODO: rename to 'evict' for consistency
-bool e4crypt_lock_user_key(userid_t user_id) {
- LOG(DEBUG) << "e4crypt_lock_user_key " << user_id;
- if (e4crypt_is_native()) {
+bool fscrypt_lock_user_key(userid_t user_id) {
+ LOG(DEBUG) << "fscrypt_lock_user_key " << user_id;
+ if (fscrypt_is_native()) {
return evict_ce_key(user_id);
- } else if (e4crypt_is_emulated()) {
+ } else if (fscrypt_is_emulated()) {
// When in emulation mode, we just use chmod
if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
!emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
@@ -651,9 +651,9 @@
return true;
}
-bool e4crypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
+bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
int flags) {
- LOG(DEBUG) << "e4crypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
+ LOG(DEBUG) << "fscrypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
<< ", user " << user_id << ", serial " << serial << ", flags " << flags;
if (flags & android::os::IVold::STORAGE_FLAG_DE) {
@@ -672,7 +672,8 @@
if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
#if MANAGE_MISC_DIRS
if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
- multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
+ multiuser_get_uid(user_id, AID_EVERYBODY)))
+ return false;
#endif
if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
@@ -682,7 +683,7 @@
}
if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
PolicyKeyRef de_ref;
if (volume_uuid.empty()) {
if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_ref.key_raw_ref)) return false;
@@ -713,7 +714,7 @@
if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
PolicyKeyRef ce_ref;
if (volume_uuid.empty()) {
if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_ref.key_raw_ref)) return false;
@@ -742,8 +743,8 @@
return true;
}
-bool e4crypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
- LOG(DEBUG) << "e4crypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
+bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
+ LOG(DEBUG) << "fscrypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
<< ", user " << user_id << ", flags " << flags;
bool res = true;
@@ -764,7 +765,7 @@
res &= destroy_dir(misc_ce_path);
res &= destroy_dir(vendor_ce_path);
} else {
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
res &= destroy_volkey(misc_ce_path, volume_uuid);
}
}
@@ -793,7 +794,7 @@
res &= destroy_dir(misc_de_path);
res &= destroy_dir(vendor_de_path);
} else {
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
res &= destroy_volkey(misc_de_path, volume_uuid);
}
}
@@ -828,9 +829,9 @@
return res;
}
-bool e4crypt_destroy_volume_keys(const std::string& volume_uuid) {
+bool fscrypt_destroy_volume_keys(const std::string& volume_uuid) {
bool res = true;
- LOG(DEBUG) << "e4crypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
+ LOG(DEBUG) << "fscrypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
res &= android::vold::runSecdiscardSingle(secdiscardable_path);
res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
diff --git a/Ext4Crypt.h b/FsCrypt.h
similarity index 61%
rename from Ext4Crypt.h
rename to FsCrypt.h
index a43a68a..16e2f9a 100644
--- a/Ext4Crypt.h
+++ b/FsCrypt.h
@@ -18,21 +18,21 @@
#include <cutils/multiuser.h>
-bool e4crypt_initialize_global_de();
+bool fscrypt_initialize_global_de();
-bool e4crypt_init_user0();
-bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral);
-bool e4crypt_destroy_user_key(userid_t user_id);
-bool e4crypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token,
+bool fscrypt_init_user0();
+bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral);
+bool fscrypt_destroy_user_key(userid_t user_id);
+bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token,
const std::string& secret);
-bool e4crypt_fixate_newest_user_key_auth(userid_t user_id);
+bool fscrypt_fixate_newest_user_key_auth(userid_t user_id);
-bool e4crypt_unlock_user_key(userid_t user_id, int serial, const std::string& token,
+bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token,
const std::string& secret);
-bool e4crypt_lock_user_key(userid_t user_id);
+bool fscrypt_lock_user_key(userid_t user_id);
-bool e4crypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
+bool fscrypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
int flags);
-bool e4crypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags);
+bool fscrypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags);
-bool e4crypt_destroy_volume_keys(const std::string& volume_uuid);
+bool fscrypt_destroy_volume_keys(const std::string& volume_uuid);
diff --git a/IdleMaint.cpp b/IdleMaint.cpp
index 5a19b8c..bca22f6 100644
--- a/IdleMaint.cpp
+++ b/IdleMaint.cpp
@@ -24,18 +24,20 @@
#include <android-base/chrono_utils.h>
#include <android-base/file.h>
-#include <android-base/stringprintf.h>
#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android/hardware/health/storage/1.0/IStorage.h>
#include <fs_mgr.h>
-#include <private/android_filesystem_config.h>
#include <hardware_legacy/power.h>
+#include <private/android_filesystem_config.h>
#include <dirent.h>
+#include <fcntl.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
-#include <fcntl.h>
using android::base::Basename;
using android::base::ReadFileToString;
@@ -43,6 +45,13 @@
using android::base::StringPrintf;
using android::base::Timer;
using android::base::WriteStringToFile;
+using android::fs_mgr::Fstab;
+using android::fs_mgr::ReadDefaultFstab;
+using android::hardware::Return;
+using android::hardware::Void;
+using android::hardware::health::storage::V1_0::IStorage;
+using android::hardware::health::storage::V1_0::IGarbageCollectCallback;
+using android::hardware::health::storage::V1_0::Result;
namespace android {
namespace vold {
@@ -73,8 +82,7 @@
static std::condition_variable cv_abort, cv_stop;
static std::mutex cv_m;
-static void addFromVolumeManager(std::list<std::string>* paths,
- PathTypes path_type) {
+static void addFromVolumeManager(std::list<std::string>* paths, PathTypes path_type) {
VolumeManager* vm = VolumeManager::Instance();
std::list<std::string> privateIds;
vm->listVolumes(VolumeBase::Type::kPrivate, privateIds);
@@ -88,57 +96,51 @@
const std::string& fs_type = vol->getFsType();
if (fs_type == "f2fs" && (Realpath(vol->getRawDmDevPath(), &gc_path) ||
Realpath(vol->getRawDevPath(), &gc_path))) {
- paths->push_back(std::string("/sys/fs/") + fs_type +
- "/" + Basename(gc_path));
+ paths->push_back(std::string("/sys/fs/") + fs_type + "/" + Basename(gc_path));
}
}
-
}
}
}
static void addFromFstab(std::list<std::string>* paths, PathTypes path_type) {
- std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
- fs_mgr_free_fstab);
- struct fstab_rec *prev_rec = NULL;
+ Fstab fstab;
+ ReadDefaultFstab(&fstab);
- for (int i = 0; i < fstab->num_entries; i++) {
- auto fs_type = std::string(fstab->recs[i].fs_type);
- /* Skip raw partitions */
- if (fs_type == "emmc" || fs_type == "mtd") {
+ std::string previous_mount_point;
+ for (const auto& entry : fstab) {
+ // Skip raw partitions.
+ if (entry.fs_type == "emmc" || entry.fs_type == "mtd") {
continue;
}
- /* Skip read-only filesystems */
- if (fstab->recs[i].flags & MS_RDONLY) {
+ // Skip read-only filesystems
+ if (entry.flags & MS_RDONLY) {
continue;
}
- if (fs_mgr_is_voldmanaged(&fstab->recs[i])) {
- continue; /* Should we trim fat32 filesystems? */
+ if (entry.fs_mgr_flags.vold_managed) {
+ continue; // Should we trim fat32 filesystems?
}
- if (fs_mgr_is_notrim(&fstab->recs[i])) {
+ if (entry.fs_mgr_flags.no_trim) {
continue;
}
- /* Skip the multi-type partitions, which are required to be following each other.
- * See fs_mgr.c's mount_with_alternatives().
- */
- if (prev_rec && !strcmp(prev_rec->mount_point, fstab->recs[i].mount_point)) {
+ // Skip the multi-type partitions, which are required to be following each other.
+ // See fs_mgr.c's mount_with_alternatives().
+ if (entry.mount_point == previous_mount_point) {
continue;
}
if (path_type == PathTypes::kMountPoint) {
- paths->push_back(fstab->recs[i].mount_point);
+ paths->push_back(entry.mount_point);
} else if (path_type == PathTypes::kBlkDevice) {
std::string gc_path;
- if (std::string(fstab->recs[i].fs_type) == "f2fs" &&
- Realpath(android::vold::BlockDeviceForPath(
- std::string(fstab->recs[i].mount_point) + "/"), &gc_path)) {
- paths->push_back(std::string("/sys/fs/") + fstab->recs[i].fs_type +
- "/" + Basename(gc_path));
+ if (entry.fs_type == "f2fs" &&
+ Realpath(android::vold::BlockDeviceForPath(entry.mount_point + "/"), &gc_path)) {
+ paths->push_back("/sys/fs/" + entry.fs_type + "/" + Basename(gc_path));
}
}
- prev_rec = &fstab->recs[i];
+ previous_mount_point = entry.mount_point;
}
}
@@ -177,8 +179,8 @@
}
} else {
nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
- LOG(INFO) << "Trimmed " << range.len << " bytes on " << path
- << " in " << nanoseconds_to_milliseconds(time) << "ms";
+ LOG(INFO) << "Trimmed " << range.len << " bytes on " << path << " in "
+ << nanoseconds_to_milliseconds(time) << "ms";
extras.putLong(String16("bytes"), range.len);
extras.putLong(String16("time"), time);
if (listener) {
@@ -223,8 +225,8 @@
}
lk.lock();
- aborted = cv_abort.wait_for(lk, 10s, []{
- return idle_maint_stat == IdleMaintStats::kAbort;});
+ aborted =
+ cv_abort.wait_for(lk, 10s, [] { return idle_maint_stat == IdleMaintStats::kAbort; });
lk.unlock();
}
@@ -234,9 +236,6 @@
static int startGc(const std::list<std::string>& paths) {
for (const auto& path : paths) {
LOG(DEBUG) << "Start GC on " << path;
- if (!WriteStringToFile("1", path + "/discard_granularity")) {
- PLOG(WARNING) << "Set discard gralunarity failed on" << path;
- }
if (!WriteStringToFile("1", path + "/gc_urgent")) {
PLOG(WARNING) << "Start GC failed on " << path;
}
@@ -250,30 +249,26 @@
if (!WriteStringToFile("0", path + "/gc_urgent")) {
PLOG(WARNING) << "Stop GC failed on " << path;
}
- if (!WriteStringToFile("16", path + "/discard_granularity")) {
- PLOG(WARNING) << "Set discard gralunarity failed on" << path;
- }
}
return android::OK;
}
-static void runDevGc(void) {
- std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
- fs_mgr_free_fstab);
- struct fstab_rec *rec = NULL;
+static void runDevGcFstab(void) {
+ Fstab fstab;
+ ReadDefaultFstab(&fstab);
- for (int i = 0; i < fstab->num_entries; i++) {
- if (fs_mgr_has_sysfs_path(&fstab->recs[i])) {
- rec = &fstab->recs[i];
+ std::string path;
+ for (const auto& entry : fstab) {
+ if (!entry.sysfs_path.empty()) {
+ path = entry.sysfs_path;
break;
}
}
- if (!rec) {
+
+ if (path.empty()) {
return;
}
- std::string path;
- path.append(rec->sysfs_path);
path = path + "/manual_gc";
Timer timer;
@@ -284,7 +279,7 @@
PLOG(WARNING) << "Reading manual_gc failed in " << path;
break;
}
-
+ require = android::base::Trim(require);
if (require == "" || require == "off" || require == "disabled") {
LOG(DEBUG) << "No more to do Dev GC";
break;
@@ -309,6 +304,57 @@
return;
}
+class GcCallback : public IGarbageCollectCallback {
+ public:
+ Return<void> onFinish(Result result) override {
+ std::unique_lock<std::mutex> lock(mMutex);
+ mFinished = true;
+ mResult = result;
+ lock.unlock();
+ mCv.notify_all();
+ return Void();
+ }
+ void wait(uint64_t seconds) {
+ std::unique_lock<std::mutex> lock(mMutex);
+ mCv.wait_for(lock, std::chrono::seconds(seconds), [this] { return mFinished; });
+
+ if (!mFinished) {
+ LOG(WARNING) << "Dev GC on HAL timeout";
+ } else if (mResult != Result::SUCCESS) {
+ LOG(WARNING) << "Dev GC on HAL failed with " << toString(mResult);
+ } else {
+ LOG(INFO) << "Dev GC on HAL successful";
+ }
+ }
+
+ private:
+ std::mutex mMutex;
+ std::condition_variable mCv;
+ bool mFinished{false};
+ Result mResult{Result::UNKNOWN_ERROR};
+};
+
+static void runDevGcOnHal(sp<IStorage> service) {
+ LOG(DEBUG) << "Start Dev GC on HAL";
+ sp<GcCallback> cb = new GcCallback();
+ auto ret = service->garbageCollect(DEVGC_TIMEOUT_SEC, cb);
+ if (!ret.isOk()) {
+ LOG(WARNING) << "Cannot start Dev GC on HAL: " << ret.description();
+ return;
+ }
+ cb->wait(DEVGC_TIMEOUT_SEC);
+}
+
+static void runDevGc(void) {
+ auto service = IStorage::getService();
+ if (service != nullptr) {
+ runDevGcOnHal(service);
+ } else {
+ // fallback to legacy code path
+ runDevGcFstab();
+ }
+}
+
int RunIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
std::unique_lock<std::mutex> lk(cv_m);
if (idle_maint_stat != IdleMaintStats::kStopped) {
@@ -369,8 +415,7 @@
cv_abort.notify_one();
lk.lock();
LOG(DEBUG) << "aborting idle maintenance";
- cv_stop.wait(lk, []{
- return idle_maint_stat == IdleMaintStats::kStopped;});
+ cv_stop.wait(lk, [] { return idle_maint_stat == IdleMaintStats::kStopped; });
}
lk.unlock();
diff --git a/KeyBuffer.cpp b/KeyBuffer.cpp
index e7aede5..5633bf8 100644
--- a/KeyBuffer.cpp
+++ b/KeyBuffer.cpp
@@ -34,4 +34,3 @@
} // namespace vold
} // namespace android
-
diff --git a/KeyBuffer.h b/KeyBuffer.h
index 2087187..a68311f 100644
--- a/KeyBuffer.h
+++ b/KeyBuffer.h
@@ -33,17 +33,15 @@
#define OPTNONE __attribute__((optimize("O0")))
#endif // not __clang__
inline OPTNONE void* memset_s(void* s, int c, size_t n) {
- if (!s)
- return s;
+ if (!s) return s;
return memset(s, c, n);
}
#undef OPTNONE
// Allocator that delegates useful work to standard one but zeroes data before deallocating.
class ZeroingAllocator : public std::allocator<char> {
- public:
- void deallocate(pointer p, size_type n)
- {
+ public:
+ void deallocate(pointer p, size_type n) {
memset_s(p, 0, n);
std::allocator<char>::deallocate(p, n);
}
@@ -60,4 +58,3 @@
} // namespace android
#endif
-
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index 6fc7250..d00225b 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -147,33 +147,6 @@
return true;
}
-static bool writeStringToFile(const std::string& payload, const std::string& filename) {
- android::base::unique_fd fd(TEMP_FAILURE_RETRY(
- open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
- if (fd == -1) {
- PLOG(ERROR) << "Failed to open " << filename;
- return false;
- }
- if (!android::base::WriteStringToFd(payload, fd)) {
- PLOG(ERROR) << "Failed to write to " << filename;
- unlink(filename.c_str());
- return false;
- }
- // fsync as close won't guarantee flush data
- // see close(2), fsync(2) and b/68901441
- if (fsync(fd) == -1) {
- if (errno == EROFS || errno == EINVAL) {
- PLOG(WARNING) << "Skip fsync " << filename
- << " on a file system does not support synchronization";
- } else {
- PLOG(ERROR) << "Failed to fsync " << filename;
- unlink(filename.c_str());
- return false;
- }
- }
- return true;
-}
-
static bool readRandomBytesOrLog(size_t count, std::string* out) {
auto status = ReadRandomBytes(count, *out);
if (status != OK) {
@@ -202,7 +175,7 @@
km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
const km::AuthorizationSet& opParams,
const km::HardwareAuthToken& authToken,
- km::AuthorizationSet* outParams) {
+ km::AuthorizationSet* outParams, bool keepOld) {
auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
std::string kmKey;
if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
@@ -219,16 +192,18 @@
if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
- if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
- PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
- return KeymasterOperation();
- }
- if (!android::vold::FsyncDirectory(dir)) {
- LOG(ERROR) << "Key dir sync failed: " << dir;
- return KeymasterOperation();
- }
- if (!keymaster.deleteKey(kmKey)) {
- LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
+ if (!keepOld) {
+ if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
+ PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
+ return KeymasterOperation();
+ }
+ if (!android::vold::FsyncDirectory(dir)) {
+ LOG(ERROR) << "Key dir sync failed: " << dir;
+ return KeymasterOperation();
+ }
+ if (!keymaster.deleteKey(kmKey)) {
+ LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
+ }
}
kmKey = newKey;
LOG(INFO) << "Key upgraded: " << dir;
@@ -237,12 +212,12 @@
static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
const km::AuthorizationSet& keyParams,
- const km::HardwareAuthToken& authToken,
- const KeyBuffer& message, std::string* ciphertext) {
+ const km::HardwareAuthToken& authToken, const KeyBuffer& message,
+ std::string* ciphertext, bool keepOld) {
km::AuthorizationSet opParams;
km::AuthorizationSet outParams;
- auto opHandle =
- begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken, &outParams);
+ auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
+ &outParams, keepOld);
if (!opHandle) return false;
auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
if (!nonceBlob.isOk()) {
@@ -266,13 +241,14 @@
static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
const km::AuthorizationSet& keyParams,
const km::HardwareAuthToken& authToken,
- const std::string& ciphertext, KeyBuffer* message) {
+ const std::string& ciphertext, KeyBuffer* message,
+ bool keepOld) {
auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
km::support::blob2hidlVec(nonce));
- auto opHandle =
- begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken, nullptr);
+ auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
+ nullptr, keepOld);
if (!opHandle) return false;
if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
if (!opHandle.finish(nullptr)) return false;
@@ -478,7 +454,8 @@
km::AuthorizationSet keyParams;
km::HardwareAuthToken authToken;
std::tie(keyParams, authToken) = beginParams(auth, appId);
- if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey))
+ if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
+ false))
return false;
} else {
if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
@@ -507,7 +484,8 @@
return true;
}
-bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
+bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
+ bool keepOld) {
std::string version;
if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
if (version != kCurrentVersion) {
@@ -532,7 +510,8 @@
km::AuthorizationSet keyParams;
km::HardwareAuthToken authToken;
std::tie(keyParams, authToken) = beginParams(auth, appId);
- if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key))
+ if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
+ keepOld))
return false;
} else {
if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
@@ -573,7 +552,10 @@
success &= deleteKey(dir);
}
auto secdiscard_cmd = std::vector<std::string>{
- kSecdiscardPath, "--", dir + "/" + kFn_encrypted_key, dir + "/" + kFn_secdiscardable,
+ kSecdiscardPath,
+ "--",
+ dir + "/" + kFn_encrypted_key,
+ dir + "/" + kFn_secdiscardable,
};
if (uses_km) {
secdiscard_cmd.emplace_back(dir + "/" + kFn_keymaster_key_blob);
diff --git a/KeyStorage.h b/KeyStorage.h
index 786e5b4..276b6b9 100644
--- a/KeyStorage.h
+++ b/KeyStorage.h
@@ -31,7 +31,7 @@
// If only "secret" is nonempty, it is used to decrypt in a non-Keymaster process.
class KeyAuthentication {
public:
- KeyAuthentication(std::string t, std::string s) : token{t}, secret{s} {};
+ KeyAuthentication(const std::string& t, const std::string& s) : token{t}, secret{s} {};
bool usesKeymaster() const { return !token.empty() || secret.empty(); };
@@ -61,7 +61,8 @@
const KeyAuthentication& auth, const KeyBuffer& key);
// Retrieve the key from the named directory.
-bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key);
+bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
+ bool keepOld = false);
// Securely destroy the key stored in the named directory and delete the directory.
bool destroyKey(const std::string& dir);
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index 9885440..12cae9b 100644
--- a/KeyUtil.cpp
+++ b/KeyUtil.cpp
@@ -16,6 +16,7 @@
#include "KeyUtil.h"
+#include <linux/fs.h>
#include <iomanip>
#include <sstream>
#include <string>
@@ -32,22 +33,10 @@
namespace android {
namespace vold {
-// ext4enc:TODO get this const from somewhere good
-const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
-
-// ext4enc:TODO Include structure from somewhere sensible
-// MUST be in sync with ext4_crypto.c in kernel
-constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
-constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
-constexpr int EXT4_MAX_KEY_SIZE = 64;
-struct ext4_encryption_key {
- uint32_t mode;
- char raw[EXT4_MAX_KEY_SIZE];
- uint32_t size;
-};
+constexpr int FS_AES_256_XTS_KEY_SIZE = 64;
bool randomKey(KeyBuffer* key) {
- *key = KeyBuffer(EXT4_AES_256_XTS_KEY_SIZE);
+ *key = KeyBuffer(FS_AES_256_XTS_KEY_SIZE);
if (ReadRandomBytes(key->size(), key->data()) != 0) {
// TODO status_t plays badly with PLOG, fix it.
LOG(ERROR) << "Random read failed";
@@ -57,7 +46,7 @@
}
// Get raw keyref - used to make keyname and to pass to ioctl
-static std::string generateKeyRef(const char* key, int length) {
+static std::string generateKeyRef(const uint8_t* key, int length) {
SHA512_CTX c;
SHA512_Init(&c);
@@ -70,30 +59,24 @@
unsigned char key_ref2[SHA512_DIGEST_LENGTH];
SHA512_Final(key_ref2, &c);
- static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
- "Hash too short for descriptor");
- return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
+ static_assert(FS_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH, "Hash too short for descriptor");
+ return std::string((char*)key_ref2, FS_KEY_DESCRIPTOR_SIZE);
}
-static bool fillKey(const KeyBuffer& key, ext4_encryption_key* ext4_key) {
- if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
+static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
+ if (key.size() != FS_AES_256_XTS_KEY_SIZE) {
LOG(ERROR) << "Wrong size key " << key.size();
return false;
}
- static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
- ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
- ext4_key->size = key.size();
- memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
- memcpy(ext4_key->raw, key.data(), key.size());
+ static_assert(FS_AES_256_XTS_KEY_SIZE <= sizeof(fs_key->raw), "Key too long!");
+ fs_key->mode = FS_ENCRYPTION_MODE_AES_256_XTS;
+ fs_key->size = key.size();
+ memset(fs_key->raw, 0, sizeof(fs_key->raw));
+ memcpy(fs_key->raw, key.data(), key.size());
return true;
}
-static char const* const NAME_PREFIXES[] = {
- "ext4",
- "f2fs",
- "fscrypt",
- nullptr
-};
+static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
static std::string keyname(const std::string& prefix, const std::string& raw_ref) {
std::ostringstream o;
@@ -105,8 +88,8 @@
}
// Get the keyring we store all keys in
-static bool e4cryptKeyring(key_serial_t* device_keyring) {
- *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
+static bool fscryptKeyring(key_serial_t* device_keyring) {
+ *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
if (*device_keyring == -1) {
PLOG(ERROR) << "Unable to find device keyring";
return false;
@@ -117,18 +100,18 @@
// Install password into global keyring
// Return raw key reference for use in policy
bool installKey(const KeyBuffer& key, std::string* raw_ref) {
- // Place ext4_encryption_key into automatically zeroing buffer.
- KeyBuffer ext4KeyBuffer(sizeof(ext4_encryption_key));
- ext4_encryption_key &ext4_key = *reinterpret_cast<ext4_encryption_key*>(ext4KeyBuffer.data());
+ // Place fscrypt_key into automatically zeroing buffer.
+ KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
+ fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
- if (!fillKey(key, &ext4_key)) return false;
- *raw_ref = generateKeyRef(ext4_key.raw, ext4_key.size);
+ if (!fillKey(key, &fs_key)) return false;
+ *raw_ref = generateKeyRef(fs_key.raw, fs_key.size);
key_serial_t device_keyring;
- if (!e4cryptKeyring(&device_keyring)) return false;
+ if (!fscryptKeyring(&device_keyring)) return false;
for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
auto ref = keyname(*name_prefix, *raw_ref);
key_serial_t key_id =
- add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
+ add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
if (key_id == -1) {
PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
return false;
@@ -141,7 +124,7 @@
bool evictKey(const std::string& raw_ref) {
key_serial_t device_keyring;
- if (!e4cryptKeyring(&device_keyring)) return false;
+ if (!fscryptKeyring(&device_keyring)) return false;
bool success = true;
for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
auto ref = keyname(*name_prefix, raw_ref);
@@ -170,8 +153,8 @@
if (!retrieveKey(key_path, key_authentication, &key)) return false;
} else {
if (!create_if_absent) {
- LOG(ERROR) << "No key found in " << key_path;
- return false;
+ LOG(ERROR) << "No key found in " << key_path;
+ return false;
}
LOG(INFO) << "Creating new key in " << key_path;
if (!randomKey(&key)) return false;
@@ -185,20 +168,19 @@
return true;
}
-bool retrieveKey(bool create_if_absent, const std::string& key_path,
- const std::string& tmp_path, KeyBuffer* key) {
+bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
+ KeyBuffer* key, bool keepOld) {
if (pathExists(key_path)) {
LOG(DEBUG) << "Key exists, using: " << key_path;
- if (!retrieveKey(key_path, kEmptyAuthentication, key)) return false;
+ if (!retrieveKey(key_path, kEmptyAuthentication, key, keepOld)) return false;
} else {
if (!create_if_absent) {
- LOG(ERROR) << "No key found in " << key_path;
- return false;
+ LOG(ERROR) << "No key found in " << key_path;
+ return false;
}
LOG(INFO) << "Creating new key in " << key_path;
if (!randomKey(key)) return false;
- if (!storeKeyAtomically(key_path, tmp_path,
- kEmptyAuthentication, *key)) return false;
+ if (!storeKeyAtomically(key_path, tmp_path, kEmptyAuthentication, *key)) return false;
}
return true;
}
diff --git a/KeyUtil.h b/KeyUtil.h
index a85eca1..7ee6725 100644
--- a/KeyUtil.h
+++ b/KeyUtil.h
@@ -20,8 +20,8 @@
#include "KeyBuffer.h"
#include "KeyStorage.h"
-#include <string>
#include <memory>
+#include <string>
namespace android {
namespace vold {
@@ -32,8 +32,8 @@
bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
const std::string& key_path, const std::string& tmp_path,
std::string* key_ref);
-bool retrieveKey(bool create_if_absent, const std::string& key_path,
- const std::string& tmp_path, KeyBuffer* key);
+bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
+ KeyBuffer* key, bool keepOld = true);
} // namespace vold
} // namespace android
diff --git a/Keymaster.h b/Keymaster.h
index fabe0f4..42a2b5d 100644
--- a/Keymaster.h
+++ b/Keymaster.h
@@ -46,8 +46,8 @@
~KeymasterOperation();
// Is this instance valid? This is false if creation fails, and becomes
// false on finish or if an update fails.
- explicit operator bool() { return mError == km::ErrorCode::OK; }
- km::ErrorCode errorCode() { return mError; }
+ explicit operator bool() const { return mError == km::ErrorCode::OK; }
+ km::ErrorCode errorCode() const { return mError; }
// Call "update" repeatedly until all of the input is consumed, and
// concatenate the output. Return true on success.
template <class TI, class TO>
diff --git a/Loop.cpp b/Loop.cpp
index 335ca13..fa8f8ba 100644
--- a/Loop.cpp
+++ b/Loop.cpp
@@ -16,24 +16,24 @@
#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <errno.h>
#include <string.h>
+#include <unistd.h>
-#include <sys/mount.h>
-#include <sys/types.h>
-#include <sys/stat.h>
#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include <linux/kdev_t.h>
#include <android-base/logging.h>
-#include <android-base/strings.h>
#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <utils/Trace.h>
@@ -45,6 +45,7 @@
using android::base::unique_fd;
static const char* kVoldPrefix = "vold:";
+static constexpr size_t kLoopDeviceRetryAttempts = 3u;
int Loop::create(const std::string& target, std::string& out_device) {
unique_fd ctl_fd(open("/dev/loop-control", O_RDWR | O_CLOEXEC));
@@ -61,7 +62,14 @@
out_device = StringPrintf("/dev/block/loop%d", num);
- unique_fd target_fd(open(target.c_str(), O_RDWR | O_CLOEXEC));
+ unique_fd target_fd;
+ for (size_t i = 0; i != kLoopDeviceRetryAttempts; ++i) {
+ target_fd.reset(open(target.c_str(), O_RDWR | O_CLOEXEC));
+ if (target_fd.get() != -1) {
+ break;
+ }
+ usleep(50000);
+ }
if (target_fd.get() == -1) {
PLOG(ERROR) << "Failed to open " << target;
return -errno;
@@ -79,7 +87,7 @@
struct loop_info64 li;
memset(&li, 0, sizeof(li));
- strlcpy((char*) li.lo_crypt_name, kVoldPrefix, LO_NAME_SIZE);
+ strlcpy((char*)li.lo_crypt_name, kVoldPrefix, LO_NAME_SIZE);
if (ioctl(device_fd.get(), LOOP_SET_STATUS64, &li) == -1) {
PLOG(ERROR) << "Failed to LOOP_SET_STATUS64";
return -errno;
@@ -88,7 +96,7 @@
return 0;
}
-int Loop::destroyByDevice(const char *loopDevice) {
+int Loop::destroyByDevice(const char* loopDevice) {
int device_fd;
device_fd = open(loopDevice, O_RDONLY | O_CLOEXEC);
@@ -138,7 +146,7 @@
continue;
}
- auto id = std::string((char*) li.lo_crypt_name);
+ auto id = std::string((char*)li.lo_crypt_name);
if (android::base::StartsWith(id, kVoldPrefix)) {
LOG(DEBUG) << "Tearing down stale loop device at " << path << " named " << id;
@@ -146,14 +154,14 @@
PLOG(WARNING) << "Failed to LOOP_CLR_FD " << path;
}
} else {
- LOG(VERBOSE) << "Found unmanaged loop device at " << path << " named " << id;
+ LOG(DEBUG) << "Found unmanaged loop device at " << path << " named " << id;
}
}
return 0;
}
-int Loop::createImageFile(const char *file, unsigned long numSectors) {
+int Loop::createImageFile(const char* file, unsigned long numSectors) {
unique_fd fd(open(file, O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0600));
if (fd.get() == -1) {
PLOG(ERROR) << "Failed to create image " << file;
@@ -169,7 +177,7 @@
return 0;
}
-int Loop::resizeImageFile(const char *file, unsigned long numSectors) {
+int Loop::resizeImageFile(const char* file, unsigned long numSectors) {
int fd;
if ((fd = open(file, O_RDWR | O_CLOEXEC)) < 0) {
diff --git a/Loop.h b/Loop.h
index 130c5b6..4e5f9c1 100644
--- a/Loop.h
+++ b/Loop.h
@@ -17,19 +17,20 @@
#ifndef _LOOP_H
#define _LOOP_H
-#include <string>
-#include <unistd.h>
#include <linux/loop.h>
+#include <unistd.h>
+#include <string>
class Loop {
-public:
+ public:
static const int LOOP_MAX = 4096;
-public:
+
+ public:
static int create(const std::string& file, std::string& out_device);
- static int destroyByDevice(const char *loopDevice);
+ static int destroyByDevice(const char* loopDevice);
static int destroyAll();
- static int createImageFile(const char *file, unsigned long numSectors);
- static int resizeImageFile(const char *file, unsigned long numSectors);
+ static int createImageFile(const char* file, unsigned long numSectors);
+ static int resizeImageFile(const char* file, unsigned long numSectors);
};
#endif
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
index c14b9a2..deb7194 100644
--- a/MetadataCrypt.cpp
+++ b/MetadataCrypt.cpp
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-#include "KeyBuffer.h"
#include "MetadataCrypt.h"
+#include "KeyBuffer.h"
+#include <algorithm>
#include <string>
#include <thread>
#include <vector>
-#include <algorithm>
#include <fcntl.h>
#include <sys/ioctl.h>
@@ -30,16 +30,18 @@
#include <linux/dm-ioctl.h>
+#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/unique_fd.h>
#include <cutils/fs.h>
#include <fs_mgr.h>
+#include "Checkpoint.h"
#include "EncryptInplace.h"
#include "KeyStorage.h"
#include "KeyUtil.h"
-#include "secontext.h"
+#include "Keymaster.h"
#include "Utils.h"
#include "VoldUtil.h"
@@ -47,19 +49,25 @@
#define TABLE_LOAD_RETRIES 10
#define DEFAULT_KEY_TARGET_TYPE "default-key"
+using android::fs_mgr::FstabEntry;
+using android::fs_mgr::GetEntryForMountPoint;
using android::vold::KeyBuffer;
static const std::string kDmNameUserdata = "userdata";
+static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
+static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
+
static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
// fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
// partitions in the fsck domain.
- if (setexeccon(secontextFsck())) {
+ if (setexeccon(android::vold::sFsckContext)) {
PLOG(ERROR) << "Failed to setexeccon";
return false;
}
- auto mount_rc = fs_mgr_do_mount(fstab_default, const_cast<char*>(mount_point),
- const_cast<char*>(blk_device), nullptr);
+ auto mount_rc = fs_mgr_do_mount(&fstab_default, const_cast<char*>(mount_point),
+ const_cast<char*>(blk_device), nullptr,
+ android::vold::cp_needsCheckpoint());
if (setexeccon(nullptr)) {
PLOG(ERROR) << "Failed to clear setexeccon";
return false;
@@ -72,12 +80,41 @@
return true;
}
-static bool read_key(struct fstab_rec const* data_rec, bool create_if_absent, KeyBuffer* key) {
- if (!data_rec->key_dir) {
+namespace android {
+namespace vold {
+
+// Note: It is possible to orphan a key if it is removed before deleting
+// Update this once keymaster APIs change, and we have a proper commit.
+static void commit_key(const std::string& dir) {
+ while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
+ LOG(ERROR) << "Wait for boot timed out";
+ }
+ Keymaster keymaster;
+ auto keyPath = dir + "/" + kFn_keymaster_key_blob;
+ auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
+ std::string key;
+
+ if (!android::base::ReadFileToString(keyPath, &key)) {
+ LOG(ERROR) << "Failed to read old key: " << dir;
+ return;
+ }
+ if (rename(newKeyPath.c_str(), keyPath.c_str()) != 0) {
+ PLOG(ERROR) << "Unable to move upgraded key to location: " << keyPath;
+ return;
+ }
+ if (!keymaster.deleteKey(key)) {
+ LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
+ }
+ LOG(INFO) << "Old Key deleted: " << dir;
+}
+
+static bool read_key(const FstabEntry& data_rec, bool create_if_absent, KeyBuffer* key) {
+ if (data_rec.key_dir.empty()) {
LOG(ERROR) << "Failed to get key_dir";
return false;
}
- std::string key_dir = data_rec->key_dir;
+ std::string key_dir = data_rec.key_dir;
+ std::string sKey;
auto dir = key_dir + "/key";
LOG(DEBUG) << "key_dir/key: " << dir;
if (fs_mkdirs(dir.c_str(), 0700)) {
@@ -85,10 +122,30 @@
return false;
}
auto temp = key_dir + "/tmp";
- if (!android::vold::retrieveKey(create_if_absent, dir, temp, key)) return false;
+ auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
+ /* If we have a leftover upgraded key, delete it.
+ * We either failed an update and must return to the old key,
+ * or we rebooted before commiting the keys in a freak accident.
+ * Either way, we can re-upgrade the key if we need to.
+ */
+ Keymaster keymaster;
+ if (pathExists(newKeyPath)) {
+ if (!android::base::ReadFileToString(newKeyPath, &sKey))
+ LOG(ERROR) << "Failed to read old key: " << dir;
+ else if (!keymaster.deleteKey(sKey))
+ LOG(ERROR) << "Old key deletion failed, continuing anyway: " << dir;
+ else
+ unlink(newKeyPath.c_str());
+ }
+ bool needs_cp = cp_needsCheckpoint();
+ if (!android::vold::retrieveKey(create_if_absent, dir, temp, key, needs_cp)) return false;
+ if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
return true;
}
+} // namespace vold
+} // namespace android
+
static KeyBuffer default_key_params(const std::string& real_blkdev, const KeyBuffer& key) {
KeyBuffer hex_key;
if (android::vold::StrToHex(key, hex_key) != android::OK) {
@@ -99,33 +156,22 @@
return res;
}
-static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t *nr_sec) {
- android::base::unique_fd dev_fd(TEMP_FAILURE_RETRY(open(
- real_blkdev.c_str(), O_RDONLY | O_CLOEXEC, 0)));
- if (dev_fd == -1) {
- PLOG(ERROR) << "Unable to open " << real_blkdev << " to measure size";
- return false;
- }
- unsigned long res;
- // TODO: should use BLKGETSIZE64
- get_blkdev_size(dev_fd.get(), &res);
- if (res == 0) {
+static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
+ if (android::vold::GetBlockDev512Sectors(real_blkdev, nr_sec) != android::OK) {
PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
return false;
}
- *nr_sec = res;
return true;
}
-static struct dm_ioctl* dm_ioctl_init(char *buffer, size_t buffer_size,
- const std::string& dm_name) {
+static struct dm_ioctl* dm_ioctl_init(char* buffer, size_t buffer_size, const std::string& dm_name) {
if (buffer_size < sizeof(dm_ioctl)) {
LOG(ERROR) << "dm_ioctl buffer too small";
return nullptr;
}
memset(buffer, 0, buffer_size);
- struct dm_ioctl* io = (struct dm_ioctl*) buffer;
+ struct dm_ioctl* io = (struct dm_ioctl*)buffer;
io->data_size = buffer_size;
io->data_start = sizeof(struct dm_ioctl);
io->version[0] = 4;
@@ -139,8 +185,8 @@
static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec,
const std::string& target_type, const KeyBuffer& crypt_params,
std::string* crypto_blkdev) {
- android::base::unique_fd dm_fd(TEMP_FAILURE_RETRY(open(
- "/dev/device-mapper", O_RDWR | O_CLOEXEC, 0)));
+ android::base::unique_fd dm_fd(
+ TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC, 0)));
if (dm_fd == -1) {
PLOG(ERROR) << "Cannot open device-mapper";
return false;
@@ -158,13 +204,13 @@
PLOG(ERROR) << "Cannot retrieve dm-crypt device status " << dm_name;
return false;
}
- *crypto_blkdev = std::string() + "/dev/block/dm-" + std::to_string(
- (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00));
+ *crypto_blkdev = std::string() + "/dev/block/dm-" +
+ std::to_string((io->dev & 0xff) | ((io->dev >> 12) & 0xfff00));
io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
size_t paramix = io->data_start + sizeof(struct dm_target_spec);
size_t nullix = paramix + crypt_params.size();
- size_t endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary
+ size_t endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary
if (endix > sizeof(buffer)) {
LOG(ERROR) << "crypt_params too big for DM_CRYPT_BUF_SIZE";
@@ -172,21 +218,21 @@
}
io->target_count = 1;
- auto tgt = (struct dm_target_spec *) (buffer + io->data_start);
+ auto tgt = (struct dm_target_spec*)(buffer + io->data_start);
tgt->status = 0;
tgt->sector_start = 0;
tgt->length = nr_sec;
target_type.copy(tgt->target_type, sizeof(tgt->target_type));
memcpy(buffer + paramix, crypt_params.data(),
- std::min(crypt_params.size(), sizeof(buffer) - paramix));
+ std::min(crypt_params.size(), sizeof(buffer) - paramix));
buffer[nullix] = '\0';
tgt->next = endix;
- for (int i = 0; ; i++) {
+ for (int i = 0;; i++) {
if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) {
break;
}
- if (i+1 >= TABLE_LOAD_RETRIES) {
+ if (i + 1 >= TABLE_LOAD_RETRIES) {
PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed";
return false;
}
@@ -203,20 +249,21 @@
return true;
}
-bool e4crypt_mount_metadata_encrypted(const std::string& mount_point, bool needs_encrypt) {
- LOG(DEBUG) << "e4crypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
+bool fscrypt_mount_metadata_encrypted(const std::string& mount_point, bool needs_encrypt) {
+ LOG(DEBUG) << "fscrypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
if (encrypted_state != "") {
- LOG(DEBUG) << "e4crypt_enable_crypto got unexpected starting state: " << encrypted_state;
+ LOG(DEBUG) << "fscrypt_enable_crypto got unexpected starting state: " << encrypted_state;
return false;
}
- auto data_rec = fs_mgr_get_entry_for_mount_point(fstab_default, mount_point);
+
+ auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
if (!data_rec) {
LOG(ERROR) << "Failed to get data_rec";
return false;
}
KeyBuffer key;
- if (!read_key(data_rec, needs_encrypt, &key)) return false;
+ if (!read_key(*data_rec, needs_encrypt, &key)) return false;
uint64_t nr_sec;
if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
std::string crypto_blkdev;
@@ -227,9 +274,8 @@
if (needs_encrypt) {
LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
off64_t size_already_done = 0;
- auto rc =
- cryptfs_enable_inplace(const_cast<char*>(crypto_blkdev.c_str()), data_rec->blk_device,
- nr_sec, &size_already_done, nr_sec, 0, false);
+ auto rc = cryptfs_enable_inplace(crypto_blkdev.data(), data_rec->blk_device.data(), nr_sec,
+ &size_already_done, nr_sec, 0, false);
if (rc != 0) {
LOG(ERROR) << "Inplace crypto failed with code: " << rc;
return false;
@@ -242,6 +288,6 @@
}
LOG(DEBUG) << "Mounting metadata-encrypted filesystem:" << mount_point;
- mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
+ mount_via_fs_mgr(data_rec->mount_point.c_str(), crypto_blkdev.c_str());
return true;
}
diff --git a/MetadataCrypt.h b/MetadataCrypt.h
index 841dc97..d82a43b 100644
--- a/MetadataCrypt.h
+++ b/MetadataCrypt.h
@@ -19,6 +19,6 @@
#include <string>
-bool e4crypt_mount_metadata_encrypted(const std::string& mount_point, bool needs_encrypt);
+bool fscrypt_mount_metadata_encrypted(const std::string& mount_point, bool needs_encrypt);
#endif
diff --git a/MoveStorage.cpp b/MoveStorage.cpp
index 4624026..79a47ae 100644
--- a/MoveStorage.cpp
+++ b/MoveStorage.cpp
@@ -29,7 +29,8 @@
#include <dirent.h>
#include <sys/wait.h>
-#define CONSTRAIN(amount, low, high) ((amount) < (low) ? (low) : ((amount) > (high) ? (high) : (amount)))
+#define CONSTRAIN(amount, low, high) \
+ ((amount) < (low) ? (low) : ((amount) > (high) ? (high) : (amount)))
static const char* kPropBlockingExec = "persist.sys.blocking_exec";
@@ -48,38 +49,38 @@
static const char* kWakeLock = "MoveTask";
static void notifyProgress(int progress,
- const android::sp<android::os::IVoldTaskListener>& listener) {
+ const android::sp<android::os::IVoldTaskListener>& listener) {
if (listener) {
android::os::PersistableBundle extras;
listener->onStatus(progress, extras);
}
}
-static status_t pushBackContents(const std::string& path, std::vector<std::string>& cmd,
- bool addWildcard) {
- DIR* dir = opendir(path.c_str());
- if (dir == NULL) {
- return -1;
+static bool pushBackContents(const std::string& path, std::vector<std::string>& cmd,
+ int searchLevels) {
+ if (searchLevels == 0) {
+ cmd.emplace_back(path);
+ return true;
+ }
+ auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(path.c_str()), closedir);
+ if (!dirp) {
+ PLOG(ERROR) << "Unable to open directory: " << path;
+ return false;
}
bool found = false;
struct dirent* ent;
- while ((ent = readdir(dir)) != NULL) {
+ while ((ent = readdir(dirp.get())) != NULL) {
if ((!strcmp(ent->d_name, ".")) || (!strcmp(ent->d_name, ".."))) {
continue;
}
- if (addWildcard) {
- cmd.push_back(StringPrintf("%s/%s/*", path.c_str(), ent->d_name));
- } else {
- cmd.push_back(StringPrintf("%s/%s", path.c_str(), ent->d_name));
- }
- found = true;
+ auto subdir = path + "/" + ent->d_name;
+ found |= pushBackContents(subdir, cmd, searchLevels - 1);
}
- closedir(dir);
- return found ? OK : -1;
+ return found;
}
static status_t execRm(const std::string& path, int startProgress, int stepProgress,
- const android::sp<android::os::IVoldTaskListener>& listener) {
+ const android::sp<android::os::IVoldTaskListener>& listener) {
notifyProgress(startProgress, listener);
uint64_t expectedBytes = GetTreeBytes(path);
@@ -89,7 +90,7 @@
cmd.push_back(kRmPath);
cmd.push_back("-f"); /* force: remove without confirmation, no error if it doesn't exist */
cmd.push_back("-R"); /* recursive: remove directory contents */
- if (pushBackContents(path, cmd, true) != OK) {
+ if (!pushBackContents(path, cmd, 2)) {
LOG(WARNING) << "No contents in " << path;
return OK;
}
@@ -114,14 +115,17 @@
sleep(1);
uint64_t deltaFreeBytes = GetFreeBytes(path) - startFreeBytes;
- notifyProgress(startProgress + CONSTRAIN((int)
- ((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress), listener);
+ notifyProgress(
+ startProgress +
+ CONSTRAIN((int)((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress),
+ listener);
}
return -1;
}
static status_t execCp(const std::string& fromPath, const std::string& toPath, int startProgress,
- int stepProgress, const android::sp<android::os::IVoldTaskListener>& listener) {
+ int stepProgress,
+ const android::sp<android::os::IVoldTaskListener>& listener) {
notifyProgress(startProgress, listener);
uint64_t expectedBytes = GetTreeBytes(fromPath);
@@ -129,7 +133,7 @@
if (expectedBytes > startFreeBytes) {
LOG(ERROR) << "Data size " << expectedBytes << " is too large to fit in free space "
- << startFreeBytes;
+ << startFreeBytes;
return -1;
}
@@ -139,7 +143,7 @@
cmd.push_back("-R"); /* recurse into subdirectories (DEST must be a directory) */
cmd.push_back("-P"); /* Do not follow symlinks [default] */
cmd.push_back("-d"); /* don't dereference symlinks */
- if (pushBackContents(fromPath, cmd, false) != OK) {
+ if (!pushBackContents(fromPath, cmd, 1)) {
LOG(WARNING) << "No contents in " << fromPath;
return OK;
}
@@ -165,8 +169,10 @@
sleep(1);
uint64_t deltaFreeBytes = startFreeBytes - GetFreeBytes(toPath);
- notifyProgress(startProgress + CONSTRAIN((int)
- ((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress), listener);
+ notifyProgress(
+ startProgress +
+ CONSTRAIN((int)((deltaFreeBytes * stepProgress) / expectedBytes), 0, stepProgress),
+ listener);
}
return -1;
}
@@ -186,8 +192,8 @@
}
static status_t moveStorageInternal(const std::shared_ptr<VolumeBase>& from,
- const std::shared_ptr<VolumeBase>& to,
- const android::sp<android::os::IVoldTaskListener>& listener) {
+ const std::shared_ptr<VolumeBase>& to,
+ const android::sp<android::os::IVoldTaskListener>& listener) {
std::string fromPath;
std::string toPath;
@@ -239,17 +245,19 @@
// useful anyway.
execRm(toPath, 80, 1, listener);
fail:
+ // clang-format off
{
std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getLock());
bringOnline(from);
bringOnline(to);
}
+ // clang-format on
notifyProgress(kMoveFailedInternalError, listener);
return -1;
}
void MoveStorage(const std::shared_ptr<VolumeBase>& from, const std::shared_ptr<VolumeBase>& to,
- const android::sp<android::os::IVoldTaskListener>& listener) {
+ const android::sp<android::os::IVoldTaskListener>& listener) {
acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
android::os::PersistableBundle extras;
diff --git a/MoveStorage.h b/MoveStorage.h
index d271704..46f745f 100644
--- a/MoveStorage.h
+++ b/MoveStorage.h
@@ -24,7 +24,7 @@
namespace vold {
void MoveStorage(const std::shared_ptr<VolumeBase>& from, const std::shared_ptr<VolumeBase>& to,
- const android::sp<android::os::IVoldTaskListener>& listener);
+ const android::sp<android::os::IVoldTaskListener>& listener);
} // namespace vold
} // namespace android
diff --git a/NetlinkHandler.cpp b/NetlinkHandler.cpp
index 92131e9..d180a95 100644
--- a/NetlinkHandler.cpp
+++ b/NetlinkHandler.cpp
@@ -14,9 +14,9 @@
* limitations under the License.
*/
+#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
-#include <errno.h>
#include <string.h>
#include <android-base/logging.h>
@@ -25,12 +25,9 @@
#include "NetlinkHandler.h"
#include "VolumeManager.h"
-NetlinkHandler::NetlinkHandler(int listenerSocket) :
- NetlinkListener(listenerSocket) {
-}
+NetlinkHandler::NetlinkHandler(int listenerSocket) : NetlinkListener(listenerSocket) {}
-NetlinkHandler::~NetlinkHandler() {
-}
+NetlinkHandler::~NetlinkHandler() {}
int NetlinkHandler::start() {
return this->startListener();
@@ -40,9 +37,9 @@
return this->stopListener();
}
-void NetlinkHandler::onEvent(NetlinkEvent *evt) {
- VolumeManager *vm = VolumeManager::Instance();
- const char *subsys = evt->getSubsystem();
+void NetlinkHandler::onEvent(NetlinkEvent* evt) {
+ VolumeManager* vm = VolumeManager::Instance();
+ const char* subsys = evt->getSubsystem();
if (!subsys) {
LOG(WARNING) << "No subsystem found in netlink event";
diff --git a/NetlinkHandler.h b/NetlinkHandler.h
index 56eb23c..8af7575 100644
--- a/NetlinkHandler.h
+++ b/NetlinkHandler.h
@@ -19,16 +19,15 @@
#include <sysutils/NetlinkListener.h>
-class NetlinkHandler: public NetlinkListener {
-
-public:
+class NetlinkHandler : public NetlinkListener {
+ public:
explicit NetlinkHandler(int listenerSocket);
virtual ~NetlinkHandler();
int start(void);
int stop(void);
-protected:
- virtual void onEvent(NetlinkEvent *evt);
+ protected:
+ virtual void onEvent(NetlinkEvent* evt);
};
#endif
diff --git a/NetlinkManager.cpp b/NetlinkManager.cpp
index 409cdc8..aacf4b9 100644
--- a/NetlinkManager.cpp
+++ b/NetlinkManager.cpp
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-#include <stdio.h>
#include <errno.h>
+#include <stdio.h>
#include <string.h>
-#include <sys/socket.h>
#include <sys/select.h>
+#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
@@ -28,14 +28,13 @@
#include <android-base/logging.h>
-#include "NetlinkManager.h"
#include "NetlinkHandler.h"
+#include "NetlinkManager.h"
-NetlinkManager *NetlinkManager::sInstance = NULL;
+NetlinkManager* NetlinkManager::sInstance = NULL;
-NetlinkManager *NetlinkManager::Instance() {
- if (!sInstance)
- sInstance = new NetlinkManager();
+NetlinkManager* NetlinkManager::Instance() {
+ if (!sInstance) sInstance = new NetlinkManager();
return sInstance;
}
@@ -43,8 +42,7 @@
mBroadcaster = NULL;
}
-NetlinkManager::~NetlinkManager() {
-}
+NetlinkManager::~NetlinkManager() {}
int NetlinkManager::start() {
struct sockaddr_nl nladdr;
@@ -56,8 +54,7 @@
nladdr.nl_pid = getpid();
nladdr.nl_groups = 0xffffffff;
- if ((mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC,
- NETLINK_KOBJECT_UEVENT)) < 0) {
+ if ((mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)) < 0) {
PLOG(ERROR) << "Unable to create uevent socket";
return -1;
}
@@ -76,7 +73,7 @@
goto out;
}
- if (bind(mSock, (struct sockaddr *) &nladdr, sizeof(nladdr)) < 0) {
+ if (bind(mSock, (struct sockaddr*)&nladdr, sizeof(nladdr)) < 0) {
PLOG(ERROR) << "Unable to bind uevent socket";
goto out;
}
diff --git a/NetlinkManager.h b/NetlinkManager.h
index 9c7ba11..e31fc2e 100644
--- a/NetlinkManager.h
+++ b/NetlinkManager.h
@@ -17,32 +17,32 @@
#ifndef _NETLINKMANAGER_H
#define _NETLINKMANAGER_H
-#include <sysutils/SocketListener.h>
#include <sysutils/NetlinkListener.h>
+#include <sysutils/SocketListener.h>
class NetlinkHandler;
class NetlinkManager {
-private:
- static NetlinkManager *sInstance;
+ private:
+ static NetlinkManager* sInstance;
-private:
- SocketListener *mBroadcaster;
- NetlinkHandler *mHandler;
- int mSock;
+ private:
+ SocketListener* mBroadcaster;
+ NetlinkHandler* mHandler;
+ int mSock;
-public:
+ public:
virtual ~NetlinkManager();
int start();
int stop();
- void setBroadcaster(SocketListener *sl) { mBroadcaster = sl; }
- SocketListener *getBroadcaster() { return mBroadcaster; }
+ void setBroadcaster(SocketListener* sl) { mBroadcaster = sl; }
+ SocketListener* getBroadcaster() { return mBroadcaster; }
- static NetlinkManager *Instance();
+ static NetlinkManager* Instance();
-private:
+ private:
NetlinkManager();
};
#endif
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index c8dbf77..dcf92be 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -3,3 +3,6 @@
[Builtin Hooks Options]
clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
+
+[Hook Scripts]
+aosp_hook = ${REPO_ROOT}/frameworks/base/tools/aosp/aosp_sha.sh ${PREUPLOAD_COMMIT} "."
diff --git a/Process.cpp b/Process.cpp
index 9038af2..3d8e3d7 100644
--- a/Process.cpp
+++ b/Process.cpp
@@ -14,28 +14,28 @@
* limitations under the License.
*/
-#include <stdio.h>
-#include <unistd.h>
+#include <ctype.h>
+#include <dirent.h>
#include <errno.h>
-#include <string.h>
#include <fcntl.h>
#include <fts.h>
-#include <dirent.h>
-#include <ctype.h>
-#include <pwd.h>
-#include <stdlib.h>
#include <poll.h>
-#include <sys/stat.h>
+#include <pwd.h>
#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
#include <fstream>
#include <unordered_set>
#include <android-base/file.h>
-#include <android-base/parseint.h>
-#include <android-base/strings.h>
-#include <android-base/stringprintf.h>
#include <android-base/logging.h>
+#include <android-base/parseint.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include "Process.h"
@@ -46,18 +46,27 @@
static bool checkMaps(const std::string& path, const std::string& prefix) {
bool found = false;
- std::ifstream infile(path);
- std::string line;
- while (std::getline(infile, line)) {
+ auto file = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
+ if (!file) {
+ return false;
+ }
+
+ char* buf = nullptr;
+ size_t len = 0;
+ while (getline(&buf, &len, file.get()) != -1) {
+ std::string line(buf);
std::string::size_type pos = line.find('/');
if (pos != std::string::npos) {
line = line.substr(pos);
if (android::base::StartsWith(line, prefix)) {
LOG(WARNING) << "Found map " << path << " referencing " << line;
found = true;
+ break;
}
}
}
+ free(buf);
+
return found;
}
diff --git a/ScryptParameters.cpp b/ScryptParameters.cpp
index c0e2030..f5a964f 100644
--- a/ScryptParameters.cpp
+++ b/ScryptParameters.cpp
@@ -19,20 +19,19 @@
#include <stdlib.h>
#include <string.h>
-bool parse_scrypt_parameters(const char* paramstr, int *Nf, int *rf, int *pf) {
+bool parse_scrypt_parameters(const char* paramstr, int* Nf, int* rf, int* pf) {
int params[3] = {};
- char *token;
- char *saveptr;
+ char* token;
+ char* saveptr;
int i;
/*
* The token we're looking for should be three integers separated by
* colons (e.g., "12:8:1"). Scan the property to make sure it matches.
*/
- for (i = 0, token = strtok_r(const_cast<char *>(paramstr), ":", &saveptr);
- token != nullptr && i < 3;
- i++, token = strtok_r(nullptr, ":", &saveptr)) {
- char *endptr;
+ for (i = 0, token = strtok_r(const_cast<char*>(paramstr), ":", &saveptr);
+ token != nullptr && i < 3; i++, token = strtok_r(nullptr, ":", &saveptr)) {
+ char* endptr;
params[i] = strtol(token, &endptr, 10);
/*
@@ -45,6 +44,8 @@
if (token != nullptr) {
return false;
}
- *Nf = params[0]; *rf = params[1]; *pf = params[2];
+ *Nf = params[0];
+ *rf = params[1];
+ *pf = params[2];
return true;
}
diff --git a/ScryptParameters.h b/ScryptParameters.h
index 190842b..edb80cc 100644
--- a/ScryptParameters.h
+++ b/ScryptParameters.h
@@ -23,6 +23,6 @@
#define SCRYPT_PROP "ro.crypto.scrypt_params"
#define SCRYPT_DEFAULTS "15:3:1"
-bool parse_scrypt_parameters(const char* paramstr, int *Nf, int *rf, int *pf);
+bool parse_scrypt_parameters(const char* paramstr, int* Nf, int* rf, int* pf);
#endif
diff --git a/Utils.cpp b/Utils.cpp
index d578d79..df50658 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -19,32 +19,40 @@
#include "Process.h"
#include "sehandle.h"
+#include <android-base/chrono_utils.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
-#include <android-base/strings.h>
#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <cutils/fs.h>
#include <logwrap/logwrap.h>
#include <private/android_filesystem_config.h>
-#include <mutex>
#include <dirent.h>
#include <fcntl.h>
#include <linux/fs.h>
+#include <mntent.h>
+#include <stdio.h>
#include <stdlib.h>
+#include <unistd.h>
#include <sys/mount.h>
-#include <sys/types.h>
#include <sys/stat.h>
-#include <sys/sysmacros.h>
-#include <sys/wait.h>
#include <sys/statvfs.h>
+#include <sys/sysmacros.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <list>
+#include <mutex>
+#include <thread>
#ifndef UMOUNT_NOFOLLOW
-#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
+#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
#endif
+using namespace std::chrono_literals;
using android::base::ReadFileToString;
using android::base::StringPrintf;
@@ -82,8 +90,8 @@
mode_t mode = 0660 | S_IFBLK;
if (mknod(cpath, mode, dev) < 0) {
if (errno != EEXIST) {
- PLOG(ERROR) << "Failed to create device node for " << major(dev)
- << ":" << minor(dev) << " at " << path;
+ PLOG(ERROR) << "Failed to create device node for " << major(dev) << ":" << minor(dev)
+ << " at " << path;
res = -errno;
}
}
@@ -186,21 +194,66 @@
}
status_t BindMount(const std::string& source, const std::string& target) {
- if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
+ if (UnmountTree(target) < 0) {
+ return -errno;
+ }
+ if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
return -errno;
}
return OK;
}
+status_t Symlink(const std::string& target, const std::string& linkpath) {
+ if (Unlink(linkpath) < 0) {
+ return -errno;
+ }
+ if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
+ PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
+ return -errno;
+ }
+ return OK;
+}
+
+status_t Unlink(const std::string& linkpath) {
+ if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
+ PLOG(ERROR) << "Failed to unlink " << linkpath;
+ return -errno;
+ }
+ return OK;
+}
+
+status_t CreateDir(const std::string& dir, mode_t mode) {
+ struct stat sb;
+ if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
+ if (S_ISDIR(sb.st_mode)) {
+ return OK;
+ } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
+ PLOG(ERROR) << "Failed to unlink " << dir;
+ return -errno;
+ }
+ } else if (errno != ENOENT) {
+ PLOG(ERROR) << "Failed to stat " << dir;
+ return -errno;
+ }
+ if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
+ PLOG(ERROR) << "Failed to mkdir " << dir;
+ return -errno;
+ }
+ return OK;
+}
+
bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
auto qual = key + "=\"";
- auto start = raw.find(qual);
- if (start > 0 && raw[start - 1] != ' ') {
- start = raw.find(qual, start + 1);
+ size_t start = 0;
+ while (true) {
+ start = raw.find(qual, start);
+ if (start == std::string::npos) return false;
+ if (start == 0 || raw[start - 1] == ' ') {
+ break;
+ }
+ start += 1;
}
-
- if (start == std::string::npos) return false;
start += qual.length();
auto end = raw.find("\"", start);
@@ -210,8 +263,8 @@
return true;
}
-static status_t readMetadata(const std::string& path, std::string* fsType,
- std::string* fsUuid, std::string* fsLabel, bool untrusted) {
+static status_t readMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
+ std::string* fsLabel, bool untrusted) {
fsType->clear();
fsUuid->clear();
fsLabel->clear();
@@ -229,7 +282,7 @@
cmd.push_back(path);
std::vector<std::string> output;
- status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
+ status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
if (res != OK) {
LOG(WARNING) << "blkid failed to identify " << path;
return res;
@@ -245,112 +298,102 @@
return OK;
}
-status_t ReadMetadata(const std::string& path, std::string* fsType,
- std::string* fsUuid, std::string* fsLabel) {
+status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
+ std::string* fsLabel) {
return readMetadata(path, fsType, fsUuid, fsLabel, false);
}
-status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType,
- std::string* fsUuid, std::string* fsLabel) {
+status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
+ std::string* fsLabel) {
return readMetadata(path, fsType, fsUuid, fsLabel, true);
}
-status_t ForkExecvp(const std::vector<std::string>& args) {
- return ForkExecvp(args, nullptr);
-}
-
-status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
- std::lock_guard<std::mutex> lock(kSecurityLock);
- size_t argc = args.size();
- char** argv = (char**) calloc(argc, sizeof(char*));
- for (size_t i = 0; i < argc; i++) {
- argv[i] = (char*) args[i].c_str();
- if (i == 0) {
- LOG(VERBOSE) << args[i];
+static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
+ std::vector<const char*> argv;
+ argv.reserve(args.size() + 1);
+ for (const auto& arg : args) {
+ if (argv.empty()) {
+ LOG(DEBUG) << arg;
} else {
- LOG(VERBOSE) << " " << args[i];
+ LOG(DEBUG) << " " << arg;
}
+ argv.emplace_back(arg.data());
}
-
- if (context) {
- if (setexeccon(context)) {
- LOG(ERROR) << "Failed to setexeccon";
- abort();
- }
- }
- status_t res = android_fork_execvp(argc, argv, NULL, false, true);
- if (context) {
- if (setexeccon(nullptr)) {
- LOG(ERROR) << "Failed to setexeccon";
- abort();
- }
- }
-
- free(argv);
- return res;
+ argv.emplace_back(nullptr);
+ return argv;
}
-status_t ForkExecvp(const std::vector<std::string>& args,
- std::vector<std::string>& output) {
- return ForkExecvp(args, output, nullptr);
-}
-
-status_t ForkExecvp(const std::vector<std::string>& args,
- std::vector<std::string>& output, security_context_t context) {
- std::lock_guard<std::mutex> lock(kSecurityLock);
- std::string cmd;
- for (size_t i = 0; i < args.size(); i++) {
- cmd += args[i] + " ";
- if (i == 0) {
- LOG(VERBOSE) << args[i];
- } else {
- LOG(VERBOSE) << " " << args[i];
- }
- }
- output.clear();
-
- if (context) {
- if (setexeccon(context)) {
- LOG(ERROR) << "Failed to setexeccon";
- abort();
- }
- }
- FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
- if (context) {
- if (setexeccon(nullptr)) {
- LOG(ERROR) << "Failed to setexeccon";
- abort();
- }
- }
-
+static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
+ android::base::unique_fd ufd) {
+ std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
if (!fp) {
- PLOG(ERROR) << "Failed to popen " << cmd;
+ PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
return -errno;
}
+ if (output) output->clear();
char line[1024];
- while (fgets(line, sizeof(line), fp) != nullptr) {
- LOG(VERBOSE) << line;
- output.push_back(std::string(line));
+ while (fgets(line, sizeof(line), fp.get()) != nullptr) {
+ LOG(DEBUG) << line;
+ if (output) output->emplace_back(line);
}
- if (pclose(fp) != 0) {
- PLOG(ERROR) << "Failed to pclose " << cmd;
+ return OK;
+}
+
+status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
+ security_context_t context) {
+ auto argv = ConvertToArgv(args);
+
+ android::base::unique_fd pipe_read, pipe_write;
+ if (!android::base::Pipe(&pipe_read, &pipe_write)) {
+ PLOG(ERROR) << "Pipe in ForkExecvp";
return -errno;
}
+ pid_t pid = fork();
+ if (pid == 0) {
+ if (context) {
+ if (setexeccon(context)) {
+ LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
+ abort();
+ }
+ }
+ pipe_read.reset();
+ if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
+ PLOG(ERROR) << "dup2 in ForkExecvp";
+ _exit(EXIT_FAILURE);
+ }
+ pipe_write.reset();
+ execvp(argv[0], const_cast<char**>(argv.data()));
+ PLOG(ERROR) << "exec in ForkExecvp";
+ _exit(EXIT_FAILURE);
+ }
+ if (pid == -1) {
+ PLOG(ERROR) << "fork in ForkExecvp";
+ return -errno;
+ }
+
+ pipe_write.reset();
+ auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
+ if (st != 0) return st;
+
+ int status;
+ if (waitpid(pid, &status, 0) == -1) {
+ PLOG(ERROR) << "waitpid in ForkExecvp";
+ return -errno;
+ }
+ if (!WIFEXITED(status)) {
+ LOG(ERROR) << "Process did not exit normally, status: " << status;
+ return -ECHILD;
+ }
+ if (WEXITSTATUS(status)) {
+ LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
+ return WEXITSTATUS(status);
+ }
return OK;
}
pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
- size_t argc = args.size();
- char** argv = (char**) calloc(argc + 1, sizeof(char*));
- for (size_t i = 0; i < argc; i++) {
- argv[i] = (char*) args[i].c_str();
- if (i == 0) {
- LOG(VERBOSE) << args[i];
- } else {
- LOG(VERBOSE) << " " << args[i];
- }
- }
+ auto argv = ConvertToArgv(args);
pid_t pid = fork();
if (pid == 0) {
@@ -358,18 +401,14 @@
close(STDOUT_FILENO);
close(STDERR_FILENO);
- if (execvp(argv[0], argv)) {
- PLOG(ERROR) << "Failed to exec";
- }
-
- _exit(1);
+ execvp(argv[0], const_cast<char**>(argv.data()));
+ PLOG(ERROR) << "exec in ForkExecvpAsync";
+ _exit(EXIT_FAILURE);
}
-
if (pid == -1) {
- PLOG(ERROR) << "Failed to exec";
+ PLOG(ERROR) << "fork in ForkExecvpAsync";
+ return -1;
}
-
- free(argv);
return pid;
}
@@ -384,7 +423,7 @@
return -errno;
}
- size_t n;
+ ssize_t n;
while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
bytes -= n;
buf += n;
@@ -401,10 +440,10 @@
status_t GenerateRandomUuid(std::string& out) {
status_t res = ReadRandomBytes(16, out);
if (res == OK) {
- out[6] &= 0x0f; /* clear version */
- out[6] |= 0x40; /* set to version 4 */
- out[8] &= 0x3f; /* clear variant */
- out[8] |= 0x80; /* set to IETF variant */
+ out[6] &= 0x0f; /* clear version */
+ out[6] |= 0x40; /* set to version 4 */
+ out[8] &= 0x3f; /* clear variant */
+ out[8] |= 0x80; /* set to IETF variant */
}
return res;
}
@@ -416,24 +455,26 @@
for (size_t i = 0; i < hex.size(); i++) {
int val = 0;
switch (hex[i]) {
- case ' ': case '-': case ':': continue;
- case 'f': case 'F': val = 15; break;
- case 'e': case 'E': val = 14; break;
- case 'd': case 'D': val = 13; break;
- case 'c': case 'C': val = 12; break;
- case 'b': case 'B': val = 11; break;
- case 'a': case 'A': val = 10; break;
- case '9': val = 9; break;
- case '8': val = 8; break;
- case '7': val = 7; break;
- case '6': val = 6; break;
- case '5': val = 5; break;
- case '4': val = 4; break;
- case '3': val = 3; break;
- case '2': val = 2; break;
- case '1': val = 1; break;
- case '0': val = 0; break;
- default: return -EINVAL;
+ // clang-format off
+ case ' ': case '-': case ':': continue;
+ case 'f': case 'F': val = 15; break;
+ case 'e': case 'E': val = 14; break;
+ case 'd': case 'D': val = 13; break;
+ case 'c': case 'C': val = 12; break;
+ case 'b': case 'B': val = 11; break;
+ case 'a': case 'A': val = 10; break;
+ case '9': val = 9; break;
+ case '8': val = 8; break;
+ case '7': val = 7; break;
+ case '6': val = 6; break;
+ case '5': val = 5; break;
+ case '4': val = 4; break;
+ case '3': val = 3; break;
+ case '2': val = 2; break;
+ case '1': val = 1; break;
+ case '0': val = 0; break;
+ default: return -EINVAL;
+ // clang-format on
}
if (even) {
@@ -476,10 +517,46 @@
return StrToHex(tmp, out);
}
+status_t GetBlockDevSize(int fd, uint64_t* size) {
+ if (ioctl(fd, BLKGETSIZE64, size)) {
+ return -errno;
+ }
+
+ return OK;
+}
+
+status_t GetBlockDevSize(const std::string& path, uint64_t* size) {
+ int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
+ status_t res = OK;
+
+ if (fd < 0) {
+ return -errno;
+ }
+
+ res = GetBlockDevSize(fd, size);
+
+ close(fd);
+
+ return res;
+}
+
+status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec) {
+ uint64_t size;
+ status_t res = GetBlockDevSize(path, &size);
+
+ if (res != OK) {
+ return res;
+ }
+
+ *nr_sec = size / 512;
+
+ return OK;
+}
+
uint64_t GetFreeBytes(const std::string& path) {
struct statvfs sb;
if (statvfs(path.c_str(), &sb) == 0) {
- return (uint64_t) sb.f_bavail * sb.f_frsize;
+ return (uint64_t)sb.f_bavail * sb.f_frsize;
} else {
return -1;
}
@@ -487,7 +564,7 @@
// TODO: borrowed from frameworks/native/libs/diskusage/ which should
// eventually be migrated into system/
-static int64_t stat_size(struct stat *s) {
+static int64_t stat_size(struct stat* s) {
int64_t blksize = s->st_blksize;
// count actual blocks used instead of nominal file size
int64_t size = s->st_blocks * 512;
@@ -505,8 +582,8 @@
int64_t calculate_dir_size(int dfd) {
int64_t size = 0;
struct stat s;
- DIR *d;
- struct dirent *de;
+ DIR* d;
+ struct dirent* de;
d = fdopendir(dfd);
if (d == NULL) {
@@ -515,7 +592,7 @@
}
while ((de = readdir(d))) {
- const char *name = de->d_name;
+ const char* name = de->d_name;
if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
size += stat_size(&s);
}
@@ -524,10 +601,8 @@
/* always skip "." and ".." */
if (name[0] == '.') {
- if (name[1] == 0)
- continue;
- if ((name[1] == '.') && (name[2] == 0))
- continue;
+ if (name[1] == 0) continue;
+ if ((name[1] == '.') && (name[2] == 0)) continue;
}
subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
@@ -546,9 +621,7 @@
PLOG(WARNING) << "Failed to open " << path;
return -1;
} else {
- uint64_t res = calculate_dir_size(dirfd);
- close(dirfd);
- return res;
+ return calculate_dir_size(dirfd);
}
}
@@ -564,8 +637,7 @@
status_t WipeBlockDevice(const std::string& path) {
status_t res = -1;
const char* c_path = path.c_str();
- unsigned long nr_sec = 0;
- unsigned long long range[2];
+ uint64_t range[2] = {0, 0};
int fd = TEMP_FAILURE_RETRY(open(c_path, O_RDWR | O_CLOEXEC));
if (fd == -1) {
@@ -573,14 +645,11 @@
goto done;
}
- if ((ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
+ if (GetBlockDevSize(fd, &range[1]) != OK) {
PLOG(ERROR) << "Failed to determine size of " << path;
goto done;
}
- range[0] = 0;
- range[1] = (unsigned long long) nr_sec * 512;
-
LOG(INFO) << "About to discard " << range[1] << " on " << path;
if (ioctl(fd, BLKDISCARD, &range) == 0) {
LOG(INFO) << "Discard success on " << path;
@@ -595,8 +664,7 @@
}
static bool isValidFilename(const std::string& name) {
- if (name.empty() || (name == ".") || (name == "..")
- || (name.find('/') != std::string::npos)) {
+ if (name.empty() || (name == ".") || (name == "..") || (name.find('/') != std::string::npos)) {
return false;
} else {
return true;
@@ -691,7 +759,7 @@
}
status_t RestoreconRecursive(const std::string& path) {
- LOG(VERBOSE) << "Starting restorecon of " << path;
+ LOG(DEBUG) << "Starting restorecon of " << path;
static constexpr const char* kRestoreconString = "selinux.restorecon_recursive";
@@ -700,7 +768,7 @@
android::base::WaitForProperty(kRestoreconString, path);
- LOG(VERBOSE) << "Finished restorecon of " << path;
+ LOG(DEBUG) << "Finished restorecon of " << path;
return OK;
}
@@ -716,8 +784,7 @@
while (true) {
ssize_t size = readlinkat(dirfd, path.c_str(), &buf[0], buf.size());
// Unrecoverable error?
- if (size == -1)
- return false;
+ if (size == -1) return false;
// It fit! (If size == buf.size(), it may have been truncated.)
if (static_cast<size_t>(size) < buf.size()) {
result->assign(&buf[0], size);
@@ -732,6 +799,146 @@
return android::base::GetBoolProperty("ro.kernel.qemu", false);
}
+static status_t findMountPointsWithPrefix(const std::string& prefix,
+ std::list<std::string>& mountPoints) {
+ // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
+ // when the prefix is /foo/bar
+ std::string prefixWithSlash(prefix);
+ if (prefix.back() != '/') {
+ android::base::StringAppendF(&prefixWithSlash, "/");
+ }
+
+ std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
+ if (!mnts) {
+ PLOG(ERROR) << "Unable to open /proc/mounts";
+ return -errno;
+ }
+
+ // Some volumes can be stacked on each other, so force unmount in
+ // reverse order to give us the best chance of success.
+ struct mntent* mnt; // getmntent returns a thread local, so it's safe.
+ while ((mnt = getmntent(mnts.get())) != nullptr) {
+ auto mountPoint = std::string(mnt->mnt_dir) + "/";
+ if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
+ mountPoints.push_front(mountPoint);
+ }
+ }
+ return OK;
+}
+
+// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
+status_t UnmountTreeWithPrefix(const std::string& prefix) {
+ std::list<std::string> toUnmount;
+ status_t result = findMountPointsWithPrefix(prefix, toUnmount);
+ if (result < 0) {
+ return result;
+ }
+ for (const auto& path : toUnmount) {
+ if (umount2(path.c_str(), MNT_DETACH)) {
+ PLOG(ERROR) << "Failed to unmount " << path;
+ result = -errno;
+ }
+ }
+ return result;
+}
+
+status_t UnmountTree(const std::string& mountPoint) {
+ if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
+ errno != ENOENT) {
+ PLOG(ERROR) << "Failed to unmount " << mountPoint;
+ return -errno;
+ }
+ return OK;
+}
+
+static status_t delete_dir_contents(DIR* dir) {
+ // Shamelessly borrowed from android::installd
+ int dfd = dirfd(dir);
+ if (dfd < 0) {
+ return -errno;
+ }
+
+ status_t result = OK;
+ struct dirent* de;
+ while ((de = readdir(dir))) {
+ const char* name = de->d_name;
+ if (de->d_type == DT_DIR) {
+ /* always skip "." and ".." */
+ if (name[0] == '.') {
+ if (name[1] == 0) continue;
+ if ((name[1] == '.') && (name[2] == 0)) continue;
+ }
+
+ android::base::unique_fd subfd(
+ openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
+ if (subfd.get() == -1) {
+ PLOG(ERROR) << "Couldn't openat " << name;
+ result = -errno;
+ continue;
+ }
+ std::unique_ptr<DIR, decltype(&closedir)> subdirp(
+ android::base::Fdopendir(std::move(subfd)), closedir);
+ if (!subdirp) {
+ PLOG(ERROR) << "Couldn't fdopendir " << name;
+ result = -errno;
+ continue;
+ }
+ result = delete_dir_contents(subdirp.get());
+ if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
+ PLOG(ERROR) << "Couldn't unlinkat " << name;
+ result = -errno;
+ }
+ } else {
+ if (unlinkat(dfd, name, 0) < 0) {
+ PLOG(ERROR) << "Couldn't unlinkat " << name;
+ result = -errno;
+ }
+ }
+ }
+ return result;
+}
+
+status_t DeleteDirContentsAndDir(const std::string& pathname) {
+ status_t res = DeleteDirContents(pathname);
+ if (res < 0) {
+ return res;
+ }
+ if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
+ PLOG(ERROR) << "rmdir failed on " << pathname;
+ return -errno;
+ }
+ LOG(VERBOSE) << "Success: rmdir on " << pathname;
+ return OK;
+}
+
+status_t DeleteDirContents(const std::string& pathname) {
+ // Shamelessly borrowed from android::installd
+ std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
+ if (!dirp) {
+ if (errno == ENOENT) {
+ return OK;
+ }
+ PLOG(ERROR) << "Failed to opendir " << pathname;
+ return -errno;
+ }
+ return delete_dir_contents(dirp.get());
+}
+
+// TODO(118708649): fix duplication with init/util.h
+status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
+ android::base::Timer t;
+ while (t.duration() < timeout) {
+ struct stat sb;
+ if (stat(filename, &sb) != -1) {
+ LOG(INFO) << "wait for '" << filename << "' took " << t;
+ return 0;
+ }
+ std::this_thread::sleep_for(10ms);
+ }
+ LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
+ return -1;
+}
+
bool FsyncDirectory(const std::string& dirname) {
android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
if (fd == -1) {
@@ -750,5 +957,32 @@
return true;
}
+bool writeStringToFile(const std::string& payload, const std::string& filename) {
+ android::base::unique_fd fd(TEMP_FAILURE_RETRY(
+ open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
+ if (fd == -1) {
+ PLOG(ERROR) << "Failed to open " << filename;
+ return false;
+ }
+ if (!android::base::WriteStringToFd(payload, fd)) {
+ PLOG(ERROR) << "Failed to write to " << filename;
+ unlink(filename.c_str());
+ return false;
+ }
+ // fsync as close won't guarantee flush data
+ // see close(2), fsync(2) and b/68901441
+ if (fsync(fd) == -1) {
+ if (errno == EROFS || errno == EINVAL) {
+ PLOG(WARNING) << "Skip fsync " << filename
+ << " on a file system does not support synchronization";
+ } else {
+ PLOG(ERROR) << "Failed to fsync " << filename;
+ unlink(filename.c_str());
+ return false;
+ }
+ }
+ return true;
+}
+
} // namespace vold
} // namespace android
diff --git a/Utils.h b/Utils.h
index 533e17c..af4e401 100644
--- a/Utils.h
+++ b/Utils.h
@@ -20,12 +20,13 @@
#include "KeyBuffer.h"
#include <android-base/macros.h>
-#include <utils/Errors.h>
#include <cutils/multiuser.h>
#include <selinux/selinux.h>
+#include <utils/Errors.h>
-#include <vector>
+#include <chrono>
#include <string>
+#include <vector>
struct DIR;
@@ -56,27 +57,37 @@
/* Creates bind mount from source to target */
status_t BindMount(const std::string& source, const std::string& target);
+/** Creates a symbolic link to target */
+status_t Symlink(const std::string& target, const std::string& linkpath);
+
+/** Calls unlink(2) at linkpath */
+status_t Unlink(const std::string& linkpath);
+
+/** Creates the given directory if it is not already available */
+status_t CreateDir(const std::string& dir, mode_t mode);
+
bool FindValue(const std::string& raw, const std::string& key, std::string* value);
/* Reads filesystem metadata from device at path */
-status_t ReadMetadata(const std::string& path, std::string* fsType,
- std::string* fsUuid, std::string* fsLabel);
+status_t ReadMetadata(const std::string& path, std::string* fsType, std::string* fsUuid,
+ std::string* fsLabel);
/* Reads filesystem metadata from untrusted device at path */
-status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType,
- std::string* fsUuid, std::string* fsLabel);
+status_t ReadMetadataUntrusted(const std::string& path, std::string* fsType, std::string* fsUuid,
+ std::string* fsLabel);
/* Returns either WEXITSTATUS() status, or a negative errno */
-status_t ForkExecvp(const std::vector<std::string>& args);
-status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context);
-
-status_t ForkExecvp(const std::vector<std::string>& args,
- std::vector<std::string>& output);
-status_t ForkExecvp(const std::vector<std::string>& args,
- std::vector<std::string>& output, security_context_t context);
+status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output = nullptr,
+ security_context_t context = nullptr);
pid_t ForkExecvpAsync(const std::vector<std::string>& args);
+/* Gets block device size in bytes */
+status_t GetBlockDevSize(int fd, uint64_t* size);
+status_t GetBlockDevSize(const std::string& path, uint64_t* size);
+/* Gets block device size in 512 byte sectors */
+status_t GetBlockDev512Sectors(const std::string& path, uint64_t* nr_sec);
+
status_t ReadRandomBytes(size_t bytes, std::string& out);
status_t ReadRandomBytes(size_t bytes, char* buffer);
status_t GenerateRandomUuid(std::string& out);
@@ -125,8 +136,17 @@
/* Checks if Android is running in QEMU */
bool IsRunningInEmulator();
+status_t UnmountTreeWithPrefix(const std::string& prefix);
+status_t UnmountTree(const std::string& mountPoint);
+
+status_t DeleteDirContentsAndDir(const std::string& pathname);
+status_t DeleteDirContents(const std::string& pathname);
+
+status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout);
+
bool FsyncDirectory(const std::string& dirname);
+bool writeStringToFile(const std::string& payload, const std::string& filename);
} // namespace vold
} // namespace android
diff --git a/VoldNativeService.cpp b/VoldNativeService.cpp
index 81523c6..eb40d84 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -24,9 +24,10 @@
#include "Process.h"
#include "VolumeManager.h"
-#include "cryptfs.h"
-#include "Ext4Crypt.h"
+#include "Checkpoint.h"
+#include "FsCrypt.h"
#include "MetadataCrypt.h"
+#include "cryptfs.h"
#include <fstream>
#include <thread>
@@ -34,8 +35,8 @@
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
-#include <ext4_utils/ext4_crypt.h>
#include <fs_mgr.h>
+#include <fscrypt/fscrypt.h>
#include <private/android_filesystem_config.h>
#include <utils/Trace.h>
@@ -83,11 +84,11 @@
uid_t uid;
if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
- reinterpret_cast<int32_t*>(&uid))) {
+ reinterpret_cast<int32_t*>(&uid))) {
return ok();
} else {
return exception(binder::Status::EX_SECURITY,
- StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
+ StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
}
}
@@ -97,7 +98,7 @@
return ok();
} else {
return exception(binder::Status::EX_SECURITY,
- StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
+ StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
}
}
@@ -108,7 +109,7 @@
for (const char& c : id) {
if (!std::isalnum(c) && c != ':' && c != ',') {
return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("ID %s is malformed", id.c_str()));
+ StringPrintf("ID %s is malformed", id.c_str()));
}
}
return ok();
@@ -120,16 +121,16 @@
}
if (path[0] != '/') {
return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Path %s is relative", path.c_str()));
+ StringPrintf("Path %s is relative", path.c_str()));
}
if ((path + '/').find("/../") != std::string::npos) {
return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Path %s is shady", path.c_str()));
+ StringPrintf("Path %s is shady", path.c_str()));
}
for (const char& c : path) {
if (c == '\0' || c == '\n') {
return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Path %s is malformed", path.c_str()));
+ StringPrintf("Path %s is malformed", path.c_str()));
}
}
return ok();
@@ -140,45 +141,144 @@
for (const char& c : hex) {
if (!std::isxdigit(c) && c != ':' && c != '-') {
return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
- StringPrintf("Hex %s is malformed", hex.c_str()));
+ StringPrintf("Hex %s is malformed", hex.c_str()));
}
}
return ok();
}
-#define ENFORCE_UID(uid) { \
- binder::Status status = checkUid((uid)); \
- if (!status.isOk()) { \
- return status; \
- } \
+binder::Status checkArgumentPackageName(const std::string& packageName) {
+ // This logic is borrowed from PackageParser.java
+ bool hasSep = false;
+ bool front = true;
+
+ for (size_t i = 0; i < packageName.length(); ++i) {
+ char c = packageName[i];
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+ front = false;
+ continue;
+ }
+ if (!front) {
+ if ((c >= '0' && c <= '9') || c == '_') {
+ continue;
+ }
+ }
+ if (c == '.') {
+ hasSep = true;
+ front = true;
+ continue;
+ }
+ return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+ StringPrintf("Bad package character %c in %s", c, packageName.c_str()));
+ }
+
+ if (front) {
+ return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+ StringPrintf("Missing separator in %s", packageName.c_str()));
+ }
+
+ return ok();
}
-#define CHECK_ARGUMENT_ID(id) { \
- binder::Status status = checkArgumentId((id)); \
- if (!status.isOk()) { \
- return status; \
- } \
+binder::Status checkArgumentPackageNames(const std::vector<std::string>& packageNames) {
+ for (size_t i = 0; i < packageNames.size(); ++i) {
+ binder::Status status = checkArgumentPackageName(packageNames[i]);
+ if (!status.isOk()) {
+ return status;
+ }
+ }
+ return ok();
}
-#define CHECK_ARGUMENT_PATH(path) { \
- binder::Status status = checkArgumentPath((path)); \
- if (!status.isOk()) { \
- return status; \
- } \
+binder::Status checkArgumentSandboxId(const std::string& sandboxId) {
+ // sandboxId will be in either the format shared-<shared-user-id> or <package-name>
+ // and <shared-user-id> name has same requirements as <package-name>.
+ std::size_t nameStartIndex = 0;
+ if (android::base::StartsWith(sandboxId, "shared-")) {
+ nameStartIndex = 7; // len("shared-")
+ }
+ return checkArgumentPackageName(sandboxId.substr(nameStartIndex));
}
-#define CHECK_ARGUMENT_HEX(hex) { \
- binder::Status status = checkArgumentHex((hex)); \
- if (!status.isOk()) { \
- return status; \
- } \
+binder::Status checkArgumentSandboxIds(const std::vector<std::string>& sandboxIds) {
+ for (size_t i = 0; i < sandboxIds.size(); ++i) {
+ binder::Status status = checkArgumentSandboxId(sandboxIds[i]);
+ if (!status.isOk()) {
+ return status;
+ }
+ }
+ return ok();
}
-#define ACQUIRE_LOCK \
+#define ENFORCE_UID(uid) \
+ { \
+ binder::Status status = checkUid((uid)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define CHECK_ARGUMENT_ID(id) \
+ { \
+ binder::Status status = checkArgumentId((id)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define CHECK_ARGUMENT_PATH(path) \
+ { \
+ binder::Status status = checkArgumentPath((path)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define CHECK_ARGUMENT_HEX(hex) \
+ { \
+ binder::Status status = checkArgumentHex((hex)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define CHECK_ARGUMENT_PACKAGE_NAMES(packageNames) \
+ { \
+ binder::Status status = checkArgumentPackageNames((packageNames)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define CHECK_ARGUMENT_SANDBOX_IDS(sandboxIds) \
+ { \
+ binder::Status status = checkArgumentSandboxIds((sandboxIds)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) \
+ { \
+ binder::Status status = checkArgumentPackageName((packageName)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define CHECK_ARGUMENT_SANDBOX_ID(sandboxId) \
+ { \
+ binder::Status status = checkArgumentSandboxId((sandboxId)); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ }
+
+#define ACQUIRE_LOCK \
std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getLock()); \
ATRACE_CALL();
-#define ACQUIRE_CRYPT_LOCK \
+#define ACQUIRE_CRYPT_LOCK \
std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getCryptLock()); \
ATRACE_CALL();
@@ -196,7 +296,7 @@
return android::OK;
}
-status_t VoldNativeService::dump(int fd, const Vector<String16> & /* args */) {
+status_t VoldNativeService::dump(int fd, const Vector<String16>& /* args */) {
auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
const binder::Status dump_permission = checkPermission(kDump);
if (!dump_permission.isOk()) {
@@ -211,7 +311,7 @@
}
binder::Status VoldNativeService::setListener(
- const android::sp<android::os::IVoldListener>& listener) {
+ const android::sp<android::os::IVoldListener>& listener) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
@@ -223,12 +323,8 @@
ENFORCE_UID(AID_SYSTEM);
// Simply acquire/release each lock for watchdog
- {
- ACQUIRE_LOCK;
- }
- {
- ACQUIRE_CRYPT_LOCK;
- }
+ { ACQUIRE_LOCK; }
+ { ACQUIRE_CRYPT_LOCK; }
return ok();
}
@@ -261,11 +357,17 @@
return translate(VolumeManager::Instance()->onUserRemoved(userId));
}
-binder::Status VoldNativeService::onUserStarted(int32_t userId) {
+binder::Status VoldNativeService::onUserStarted(int32_t userId,
+ const std::vector<std::string>& packageNames,
+ const std::vector<int>& appIds,
+ const std::vector<std::string>& sandboxIds) {
ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_PACKAGE_NAMES(packageNames);
+ CHECK_ARGUMENT_SANDBOX_IDS(sandboxIds);
ACQUIRE_LOCK;
- return translate(VolumeManager::Instance()->onUserStarted(userId));
+ return translate(
+ VolumeManager::Instance()->onUserStarted(userId, packageNames, appIds, sandboxIds));
}
binder::Status VoldNativeService::onUserStopped(int32_t userId) {
@@ -275,6 +377,24 @@
return translate(VolumeManager::Instance()->onUserStopped(userId));
}
+binder::Status VoldNativeService::addAppIds(const std::vector<std::string>& packageNames,
+ const std::vector<int32_t>& appIds) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_PACKAGE_NAMES(packageNames);
+ ACQUIRE_LOCK;
+
+ return translate(VolumeManager::Instance()->addAppIds(packageNames, appIds));
+}
+
+binder::Status VoldNativeService::addSandboxIds(const std::vector<int32_t>& appIds,
+ const std::vector<std::string>& sandboxIds) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_SANDBOX_IDS(sandboxIds);
+ ACQUIRE_LOCK;
+
+ return translate(VolumeManager::Instance()->addSandboxIds(appIds, sandboxIds));
+}
+
binder::Status VoldNativeService::onSecureKeyguardStateChanged(bool isShowing) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
@@ -283,7 +403,7 @@
}
binder::Status VoldNativeService::partition(const std::string& diskId, int32_t partitionType,
- int32_t ratio) {
+ int32_t ratio) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_ID(diskId);
ACQUIRE_LOCK;
@@ -293,15 +413,19 @@
return error("Failed to find disk " + diskId);
}
switch (partitionType) {
- case PARTITION_TYPE_PUBLIC: return translate(disk->partitionPublic());
- case PARTITION_TYPE_PRIVATE: return translate(disk->partitionPrivate());
- case PARTITION_TYPE_MIXED: return translate(disk->partitionMixed(ratio));
- default: return error("Unknown type " + std::to_string(partitionType));
+ case PARTITION_TYPE_PUBLIC:
+ return translate(disk->partitionPublic());
+ case PARTITION_TYPE_PRIVATE:
+ return translate(disk->partitionPrivate());
+ case PARTITION_TYPE_MIXED:
+ return translate(disk->partitionMixed(ratio));
+ default:
+ return error("Unknown type " + std::to_string(partitionType));
}
}
binder::Status VoldNativeService::forgetPartition(const std::string& partGuid,
- const std::string& fsUuid) {
+ const std::string& fsUuid) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_HEX(partGuid);
CHECK_ARGUMENT_HEX(fsUuid);
@@ -311,7 +435,7 @@
}
binder::Status VoldNativeService::mount(const std::string& volId, int32_t mountFlags,
- int32_t mountUserId) {
+ int32_t mountUserId) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_ID(volId);
ACQUIRE_LOCK;
@@ -325,10 +449,16 @@
vol->setMountUserId(mountUserId);
int res = vol->mount();
- if ((mountFlags & MOUNT_FLAG_PRIMARY) != 0) {
- VolumeManager::Instance()->setPrimary(vol);
+ if (res != OK) {
+ return translate(res);
}
- return translate(res);
+ if ((mountFlags & MOUNT_FLAG_PRIMARY) != 0) {
+ res = VolumeManager::Instance()->setPrimary(vol);
+ if (res != OK) {
+ return translate(res);
+ }
+ }
+ return translate(OK);
}
binder::Status VoldNativeService::unmount(const std::string& volId) {
@@ -387,9 +517,7 @@
auto status = pathForVolId(volId, &path);
if (!status.isOk()) return status;
- std::thread([=]() {
- android::vold::Benchmark(path, listener);
- }).detach();
+ std::thread([=]() { android::vold::Benchmark(path, listener); }).detach();
return ok();
}
@@ -404,8 +532,9 @@
return translate(android::vold::CheckEncryption(path));
}
-binder::Status VoldNativeService::moveStorage(const std::string& fromVolId,
- const std::string& toVolId, const android::sp<android::os::IVoldTaskListener>& listener) {
+binder::Status VoldNativeService::moveStorage(
+ const std::string& fromVolId, const std::string& toVolId,
+ const android::sp<android::os::IVoldTaskListener>& listener) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_ID(fromVolId);
CHECK_ARGUMENT_ID(toVolId);
@@ -419,9 +548,7 @@
return error("Failed to find volume " + toVolId);
}
- std::thread([=]() {
- android::vold::MoveStorage(fromVol, toVol, listener);
- }).detach();
+ std::thread([=]() { android::vold::MoveStorage(fromVol, toVol, listener); }).detach();
return ok();
}
@@ -429,15 +556,7 @@
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- std::string tmp;
- switch (remountMode) {
- case REMOUNT_MODE_NONE: tmp = "none"; break;
- case REMOUNT_MODE_DEFAULT: tmp = "default"; break;
- case REMOUNT_MODE_READ: tmp = "read"; break;
- case REMOUNT_MODE_WRITE: tmp = "write"; break;
- default: return error("Unknown mode " + std::to_string(remountMode));
- }
- return translate(VolumeManager::Instance()->remountUid(uid, tmp));
+ return translate(VolumeManager::Instance()->remountUid(uid, remountMode));
}
binder::Status VoldNativeService::mkdirs(const std::string& path) {
@@ -449,14 +568,15 @@
}
binder::Status VoldNativeService::createObb(const std::string& sourcePath,
- const std::string& sourceKey, int32_t ownerGid, std::string* _aidl_return) {
+ const std::string& sourceKey, int32_t ownerGid,
+ std::string* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_PATH(sourcePath);
CHECK_ARGUMENT_HEX(sourceKey);
ACQUIRE_LOCK;
return translate(
- VolumeManager::Instance()->createObb(sourcePath, sourceKey, ownerGid, _aidl_return));
+ VolumeManager::Instance()->createObb(sourcePath, sourceKey, ownerGid, _aidl_return));
}
binder::Status VoldNativeService::destroyObb(const std::string& volId) {
@@ -467,52 +587,86 @@
return translate(VolumeManager::Instance()->destroyObb(volId));
}
-binder::Status VoldNativeService::fstrim(int32_t fstrimFlags,
- const android::sp<android::os::IVoldTaskListener>& listener) {
+binder::Status VoldNativeService::createStubVolume(
+ const std::string& sourcePath, const std::string& mountPath, const std::string& fsType,
+ const std::string& fsUuid, const std::string& fsLabel, std::string* _aidl_return) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_PATH(sourcePath);
+ CHECK_ARGUMENT_PATH(mountPath);
+ CHECK_ARGUMENT_HEX(fsUuid);
+ // Label limitation seems to be different between fs (including allowed characters), so checking
+ // is quite meaningless.
+ ACQUIRE_LOCK;
+
+ return translate(VolumeManager::Instance()->createStubVolume(sourcePath, mountPath, fsType,
+ fsUuid, fsLabel, _aidl_return));
+}
+
+binder::Status VoldNativeService::destroyStubVolume(const std::string& volId) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_ID(volId);
+ ACQUIRE_LOCK;
+
+ return translate(VolumeManager::Instance()->destroyStubVolume(volId));
+}
+
+binder::Status VoldNativeService::fstrim(
+ int32_t fstrimFlags, const android::sp<android::os::IVoldTaskListener>& listener) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- std::thread([=]() {
- android::vold::Trim(listener);
- }).detach();
+ std::thread([=]() { android::vold::Trim(listener); }).detach();
return ok();
}
binder::Status VoldNativeService::runIdleMaint(
- const android::sp<android::os::IVoldTaskListener>& listener) {
+ const android::sp<android::os::IVoldTaskListener>& listener) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- std::thread([=]() {
- android::vold::RunIdleMaint(listener);
- }).detach();
+ std::thread([=]() { android::vold::RunIdleMaint(listener); }).detach();
return ok();
}
binder::Status VoldNativeService::abortIdleMaint(
- const android::sp<android::os::IVoldTaskListener>& listener) {
+ const android::sp<android::os::IVoldTaskListener>& listener) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- std::thread([=]() {
- android::vold::AbortIdleMaint(listener);
- }).detach();
+ std::thread([=]() { android::vold::AbortIdleMaint(listener); }).detach();
return ok();
}
-binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t pid, int32_t mountId,
- android::base::unique_fd* _aidl_return) {
+binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t mountId,
+ android::base::unique_fd* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- return translate(VolumeManager::Instance()->mountAppFuse(uid, pid, mountId, _aidl_return));
+ return translate(VolumeManager::Instance()->mountAppFuse(uid, mountId, _aidl_return));
}
-binder::Status VoldNativeService::unmountAppFuse(int32_t uid, int32_t pid, int32_t mountId) {
+binder::Status VoldNativeService::unmountAppFuse(int32_t uid, int32_t mountId) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- return translate(VolumeManager::Instance()->unmountAppFuse(uid, pid, mountId));
+ return translate(VolumeManager::Instance()->unmountAppFuse(uid, mountId));
+}
+
+binder::Status VoldNativeService::openAppFuseFile(int32_t uid, int32_t mountId, int32_t fileId,
+ int32_t flags,
+ android::base::unique_fd* _aidl_return) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ int fd = VolumeManager::Instance()->openAppFuseFile(uid, mountId, fileId, flags);
+ if (fd == -1) {
+ return error("Failed to open AppFuse file for uid: " + std::to_string(uid) +
+ " mountId: " + std::to_string(mountId) + " fileId: " + std::to_string(fileId) +
+ " flags: " + std::to_string(flags));
+ }
+
+ *_aidl_return = android::base::unique_fd(fd);
+ return ok();
}
binder::Status VoldNativeService::fdeCheckPassword(const std::string& password) {
@@ -541,7 +695,7 @@
}
static int fdeEnableInternal(int32_t passwordType, const std::string& password,
- int32_t encryptionFlags) {
+ int32_t encryptionFlags) {
bool noUi = (encryptionFlags & VoldNativeService::ENCRYPTION_FLAG_NO_UI) != 0;
for (int tries = 0; tries < 2; ++tries) {
@@ -562,17 +716,17 @@
return -1;
}
-binder::Status VoldNativeService::fdeEnable(int32_t passwordType,
- const std::string& password, int32_t encryptionFlags) {
+binder::Status VoldNativeService::fdeEnable(int32_t passwordType, const std::string& password,
+ int32_t encryptionFlags) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
LOG(DEBUG) << "fdeEnable(" << passwordType << ", *, " << encryptionFlags << ")";
- if (e4crypt_is_native()) {
- LOG(ERROR) << "e4crypt_is_native, fdeEnable invalid";
- return error("e4crypt_is_native, fdeEnable invalid");
+ if (fscrypt_is_native()) {
+ LOG(ERROR) << "fscrypt_is_native, fdeEnable invalid";
+ return error("fscrypt_is_native, fdeEnable invalid");
}
- LOG(DEBUG) << "!e4crypt_is_native, spawning fdeEnableInternal";
+ LOG(DEBUG) << "!fscrypt_is_native, spawning fdeEnableInternal";
// Spawn as thread so init can issue commands back to vold without
// causing deadlock, usually as a result of prep_data_fs.
@@ -581,7 +735,7 @@
}
binder::Status VoldNativeService::fdeChangePassword(int32_t passwordType,
- const std::string& password) {
+ const std::string& password) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
@@ -595,8 +749,7 @@
return translate(cryptfs_verify_passwd(password.c_str()));
}
-binder::Status VoldNativeService::fdeGetField(const std::string& key,
- std::string* _aidl_return) {
+binder::Status VoldNativeService::fdeGetField(const std::string& key, std::string* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
@@ -609,8 +762,7 @@
}
}
-binder::Status VoldNativeService::fdeSetField(const std::string& key,
- const std::string& value) {
+binder::Status VoldNativeService::fdeSetField(const std::string& key, const std::string& value) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
@@ -648,14 +800,14 @@
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_initialize_global_de());
+ return translateBool(fscrypt_initialize_global_de());
}
binder::Status VoldNativeService::mountDefaultEncrypted() {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- if (!e4crypt_is_native()) {
+ if (!fscrypt_is_native()) {
// Spawn as thread so init can issue commands back to vold without
// causing deadlock, usually as a result of prep_data_fs.
std::thread(&cryptfs_mount_default_encrypted).detach();
@@ -667,7 +819,7 @@
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_init_user0());
+ return translateBool(fscrypt_init_user0());
}
binder::Status VoldNativeService::isConvertibleToFbe(bool* _aidl_return) {
@@ -682,81 +834,196 @@
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- return translateBool(e4crypt_mount_metadata_encrypted(mountPoint, false));
+ return translateBool(fscrypt_mount_metadata_encrypted(mountPoint, false));
}
binder::Status VoldNativeService::encryptFstab(const std::string& mountPoint) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_LOCK;
- return translateBool(e4crypt_mount_metadata_encrypted(mountPoint, true));
+ return translateBool(fscrypt_mount_metadata_encrypted(mountPoint, true));
}
-binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial,
- bool ephemeral) {
+binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial, bool ephemeral) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_vold_create_user_key(userId, userSerial, ephemeral));
+ return translateBool(fscrypt_vold_create_user_key(userId, userSerial, ephemeral));
}
binder::Status VoldNativeService::destroyUserKey(int32_t userId) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_destroy_user_key(userId));
+ return translateBool(fscrypt_destroy_user_key(userId));
}
binder::Status VoldNativeService::addUserKeyAuth(int32_t userId, int32_t userSerial,
- const std::string& token, const std::string& secret) {
+ const std::string& token,
+ const std::string& secret) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_add_user_key_auth(userId, userSerial, token, secret));
+ return translateBool(fscrypt_add_user_key_auth(userId, userSerial, token, secret));
}
binder::Status VoldNativeService::fixateNewestUserKeyAuth(int32_t userId) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_fixate_newest_user_key_auth(userId));
+ return translateBool(fscrypt_fixate_newest_user_key_auth(userId));
}
binder::Status VoldNativeService::unlockUserKey(int32_t userId, int32_t userSerial,
- const std::string& token, const std::string& secret) {
+ const std::string& token,
+ const std::string& secret) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_unlock_user_key(userId, userSerial, token, secret));
+ return translateBool(fscrypt_unlock_user_key(userId, userSerial, token, secret));
}
binder::Status VoldNativeService::lockUserKey(int32_t userId) {
ENFORCE_UID(AID_SYSTEM);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_lock_user_key(userId));
+ return translateBool(fscrypt_lock_user_key(userId));
}
binder::Status VoldNativeService::prepareUserStorage(const std::unique_ptr<std::string>& uuid,
- int32_t userId, int32_t userSerial, int32_t flags) {
+ int32_t userId, int32_t userSerial,
+ int32_t flags) {
ENFORCE_UID(AID_SYSTEM);
std::string empty_string = "";
auto uuid_ = uuid ? *uuid : empty_string;
CHECK_ARGUMENT_HEX(uuid_);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_prepare_user_storage(uuid_, userId, userSerial, flags));
+ return translateBool(fscrypt_prepare_user_storage(uuid_, userId, userSerial, flags));
}
binder::Status VoldNativeService::destroyUserStorage(const std::unique_ptr<std::string>& uuid,
- int32_t userId, int32_t flags) {
+ int32_t userId, int32_t flags) {
ENFORCE_UID(AID_SYSTEM);
std::string empty_string = "";
auto uuid_ = uuid ? *uuid : empty_string;
CHECK_ARGUMENT_HEX(uuid_);
ACQUIRE_CRYPT_LOCK;
- return translateBool(e4crypt_destroy_user_storage(uuid_, userId, flags));
+ return translateBool(fscrypt_destroy_user_storage(uuid_, userId, flags));
+}
+
+binder::Status VoldNativeService::prepareSandboxForApp(const std::string& packageName,
+ int32_t appId, const std::string& sandboxId,
+ int32_t userId) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_PACKAGE_NAME(packageName);
+ CHECK_ARGUMENT_SANDBOX_ID(sandboxId);
+ ACQUIRE_LOCK;
+
+ return translate(
+ VolumeManager::Instance()->prepareSandboxForApp(packageName, appId, sandboxId, userId));
+}
+
+binder::Status VoldNativeService::destroySandboxForApp(const std::string& packageName,
+ const std::string& sandboxId,
+ int32_t userId) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_PACKAGE_NAME(packageName);
+ CHECK_ARGUMENT_SANDBOX_ID(sandboxId);
+ ACQUIRE_LOCK;
+
+ return translate(
+ VolumeManager::Instance()->destroySandboxForApp(packageName, sandboxId, userId));
+}
+
+binder::Status VoldNativeService::startCheckpoint(int32_t retry) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ return cp_startCheckpoint(retry);
+}
+
+binder::Status VoldNativeService::needsRollback(bool* _aidl_return) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ *_aidl_return = cp_needsRollback();
+ return ok();
+}
+
+binder::Status VoldNativeService::needsCheckpoint(bool* _aidl_return) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ *_aidl_return = cp_needsCheckpoint();
+ return ok();
+}
+
+binder::Status VoldNativeService::commitChanges() {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ return cp_commitChanges();
+}
+
+binder::Status VoldNativeService::prepareCheckpoint() {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ return cp_prepareCheckpoint();
+}
+
+binder::Status VoldNativeService::restoreCheckpoint(const std::string& mountPoint) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_PATH(mountPoint);
+ ACQUIRE_LOCK;
+
+ return cp_restoreCheckpoint(mountPoint);
+}
+
+binder::Status VoldNativeService::restoreCheckpointPart(const std::string& mountPoint, int count) {
+ ENFORCE_UID(AID_SYSTEM);
+ CHECK_ARGUMENT_PATH(mountPoint);
+ ACQUIRE_LOCK;
+
+ return cp_restoreCheckpoint(mountPoint, count);
+}
+
+binder::Status VoldNativeService::markBootAttempt() {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ return cp_markBootAttempt();
+}
+
+binder::Status VoldNativeService::abortChanges(const std::string& message, bool retry) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ cp_abortChanges(message, retry);
+ return ok();
+}
+
+binder::Status VoldNativeService::supportsCheckpoint(bool* _aidl_return) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ return cp_supportsCheckpoint(*_aidl_return);
+}
+
+binder::Status VoldNativeService::supportsBlockCheckpoint(bool* _aidl_return) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ return cp_supportsBlockCheckpoint(*_aidl_return);
+}
+
+binder::Status VoldNativeService::supportsFileCheckpoint(bool* _aidl_return) {
+ ENFORCE_UID(AID_SYSTEM);
+ ACQUIRE_LOCK;
+
+ return cp_supportsFileCheckpoint(*_aidl_return);
}
} // namespace vold
diff --git a/VoldNativeService.h b/VoldNativeService.h
index 2e90101..3f5ae83 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -26,10 +26,10 @@
namespace vold {
class VoldNativeService : public BinderService<VoldNativeService>, public os::BnVold {
-public:
+ public:
static status_t start();
static char const* getServiceName() { return "vold"; }
- virtual status_t dump(int fd, const Vector<String16> &args) override;
+ virtual status_t dump(int fd, const Vector<String16>& args) override;
binder::Status setListener(const android::sp<android::os::IVoldListener>& listener);
@@ -39,9 +39,16 @@
binder::Status onUserAdded(int32_t userId, int32_t userSerial);
binder::Status onUserRemoved(int32_t userId);
- binder::Status onUserStarted(int32_t userId);
+ binder::Status onUserStarted(int32_t userId, const std::vector<std::string>& packageNames,
+ const std::vector<int>& appIds,
+ const std::vector<std::string>& sandboxIds);
binder::Status onUserStopped(int32_t userId);
+ binder::Status addAppIds(const std::vector<std::string>& packageNames,
+ const std::vector<int32_t>& appIds);
+ binder::Status addSandboxIds(const std::vector<int32_t>& appIds,
+ const std::vector<std::string>& sandboxIds);
+
binder::Status onSecureKeyguardStateChanged(bool isShowing);
binder::Status partition(const std::string& diskId, int32_t partitionType, int32_t ratio);
@@ -51,38 +58,42 @@
binder::Status unmount(const std::string& volId);
binder::Status format(const std::string& volId, const std::string& fsType);
binder::Status benchmark(const std::string& volId,
- const android::sp<android::os::IVoldTaskListener>& listener);
+ const android::sp<android::os::IVoldTaskListener>& listener);
binder::Status checkEncryption(const std::string& volId);
binder::Status moveStorage(const std::string& fromVolId, const std::string& toVolId,
- const android::sp<android::os::IVoldTaskListener>& listener);
+ const android::sp<android::os::IVoldTaskListener>& listener);
binder::Status remountUid(int32_t uid, int32_t remountMode);
binder::Status mkdirs(const std::string& path);
binder::Status createObb(const std::string& sourcePath, const std::string& sourceKey,
- int32_t ownerGid, std::string* _aidl_return);
+ int32_t ownerGid, std::string* _aidl_return);
binder::Status destroyObb(const std::string& volId);
- binder::Status fstrim(int32_t fstrimFlags,
- const android::sp<android::os::IVoldTaskListener>& listener);
- binder::Status runIdleMaint(
- const android::sp<android::os::IVoldTaskListener>& listener);
- binder::Status abortIdleMaint(
- const android::sp<android::os::IVoldTaskListener>& listener);
+ binder::Status createStubVolume(const std::string& sourcePath, const std::string& mountPath,
+ const std::string& fsType, const std::string& fsUuid,
+ const std::string& fsLabel, std::string* _aidl_return);
+ binder::Status destroyStubVolume(const std::string& volId);
- binder::Status mountAppFuse(int32_t uid, int32_t pid, int32_t mountId,
- android::base::unique_fd* _aidl_return);
- binder::Status unmountAppFuse(int32_t uid, int32_t pid, int32_t mountId);
+ binder::Status fstrim(int32_t fstrimFlags,
+ const android::sp<android::os::IVoldTaskListener>& listener);
+ binder::Status runIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener);
+ binder::Status abortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener);
+
+ binder::Status mountAppFuse(int32_t uid, int32_t mountId,
+ android::base::unique_fd* _aidl_return);
+ binder::Status unmountAppFuse(int32_t uid, int32_t mountId);
+ binder::Status openAppFuseFile(int32_t uid, int32_t mountId, int32_t fileId, int32_t flags,
+ android::base::unique_fd* _aidl_return);
binder::Status fdeCheckPassword(const std::string& password);
binder::Status fdeRestart();
binder::Status fdeComplete(int32_t* _aidl_return);
- binder::Status fdeEnable(int32_t passwordType,
- const std::string& password, int32_t encryptionFlags);
- binder::Status fdeChangePassword(int32_t passwordType,
- const std::string& password);
+ binder::Status fdeEnable(int32_t passwordType, const std::string& password,
+ int32_t encryptionFlags);
+ binder::Status fdeChangePassword(int32_t passwordType, const std::string& password);
binder::Status fdeVerifyPassword(const std::string& password);
binder::Status fdeGetField(const std::string& key, std::string* _aidl_return);
binder::Status fdeSetField(const std::string& key, const std::string& value);
@@ -101,18 +112,36 @@
binder::Status createUserKey(int32_t userId, int32_t userSerial, bool ephemeral);
binder::Status destroyUserKey(int32_t userId);
- binder::Status addUserKeyAuth(int32_t userId, int32_t userSerial,
- const std::string& token, const std::string& secret);
+ binder::Status addUserKeyAuth(int32_t userId, int32_t userSerial, const std::string& token,
+ const std::string& secret);
binder::Status fixateNewestUserKeyAuth(int32_t userId);
- binder::Status unlockUserKey(int32_t userId, int32_t userSerial,
- const std::string& token, const std::string& secret);
+ binder::Status unlockUserKey(int32_t userId, int32_t userSerial, const std::string& token,
+ const std::string& secret);
binder::Status lockUserKey(int32_t userId);
- binder::Status prepareUserStorage(const std::unique_ptr<std::string>& uuid,
- int32_t userId, int32_t userSerial, int32_t flags);
- binder::Status destroyUserStorage(const std::unique_ptr<std::string>& uuid,
- int32_t userId, int32_t flags);
+ binder::Status prepareUserStorage(const std::unique_ptr<std::string>& uuid, int32_t userId,
+ int32_t userSerial, int32_t flags);
+ binder::Status destroyUserStorage(const std::unique_ptr<std::string>& uuid, int32_t userId,
+ int32_t flags);
+
+ binder::Status prepareSandboxForApp(const std::string& packageName, int32_t appId,
+ const std::string& sandboxId, int32_t userId);
+ binder::Status destroySandboxForApp(const std::string& packageName,
+ const std::string& sandboxId, int32_t userId);
+
+ binder::Status startCheckpoint(int32_t retry);
+ binder::Status needsCheckpoint(bool* _aidl_return);
+ binder::Status needsRollback(bool* _aidl_return);
+ binder::Status commitChanges();
+ binder::Status prepareCheckpoint();
+ binder::Status restoreCheckpoint(const std::string& mountPoint);
+ binder::Status restoreCheckpointPart(const std::string& mountPoint, int count);
+ binder::Status markBootAttempt();
+ binder::Status abortChanges(const std::string& message, bool retry);
+ binder::Status supportsCheckpoint(bool* _aidl_return);
+ binder::Status supportsBlockCheckpoint(bool* _aidl_return);
+ binder::Status supportsFileCheckpoint(bool* _aidl_return);
};
} // namespace vold
diff --git a/VoldUtil.cpp b/VoldUtil.cpp
index afe8b53..082f743 100644
--- a/VoldUtil.cpp
+++ b/VoldUtil.cpp
@@ -14,13 +14,6 @@
* limitations under the License.
*/
-#include <sys/ioctl.h>
-#include <linux/fs.h>
+#include "VoldUtil.h"
-struct fstab *fstab_default;
-
-void get_blkdev_size(int fd, unsigned long* nr_sec) {
- if ((ioctl(fd, BLKGETSIZE, nr_sec)) == -1) {
- *nr_sec = 0;
- }
-}
+android::fs_mgr::Fstab fstab_default;
diff --git a/VoldUtil.h b/VoldUtil.h
index fd66672..173c598 100644
--- a/VoldUtil.h
+++ b/VoldUtil.h
@@ -14,16 +14,11 @@
* limitations under the License.
*/
-#ifndef _VOLDUTIL_H
-#define _VOLDUTIL_H
+#pragma once
#include <fstab/fstab.h>
#include <sys/cdefs.h>
-extern struct fstab *fstab_default;
+extern android::fs_mgr::Fstab fstab_default;
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
-
-void get_blkdev_size(int fd, unsigned long* nr_sec);
-
-#endif
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 8c32587..fad59f1 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -26,13 +26,15 @@
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/stat.h>
-#include <sys/types.h>
#include <sys/sysmacros.h>
+#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
+#include <array>
#include <linux/kdev_t.h>
+#include <ApexProperties.sysprop.h>
#include <android-base/logging.h>
#include <android-base/parseint.h>
#include <android-base/properties.h>
@@ -48,14 +50,16 @@
#include <private/android_filesystem_config.h>
-#include <ext4_utils/ext4_crypt.h>
+#include <fscrypt/fscrypt.h>
+#include "AppFuseUtil.h"
#include "Devmapper.h"
-#include "Ext4Crypt.h"
+#include "FsCrypt.h"
#include "Loop.h"
#include "NetlinkManager.h"
#include "Process.h"
#include "Utils.h"
+#include "VoldNativeService.h"
#include "VoldUtil.h"
#include "VolumeManager.h"
#include "cryptfs.h"
@@ -63,15 +67,32 @@
#include "fs/Vfat.h"
#include "model/EmulatedVolume.h"
#include "model/ObbVolume.h"
+#include "model/StubVolume.h"
+using android::OK;
+using android::base::GetBoolProperty;
+using android::base::StartsWith;
+using android::base::StringAppendF;
using android::base::StringPrintf;
using android::base::unique_fd;
+using android::vold::BindMount;
+using android::vold::CreateDir;
+using android::vold::DeleteDirContents;
+using android::vold::DeleteDirContentsAndDir;
+using android::vold::Symlink;
+using android::vold::Unlink;
+using android::vold::UnmountTree;
+using android::vold::VoldNativeService;
static const char* kPathUserMount = "/mnt/user";
static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
+static const char* kIsolatedStorage = "persist.sys.isolated_storage";
+static const char* kIsolatedStorageSnapshot = "sys.isolated_storage_snapshot";
static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
+static const std::string kEmptyString("");
+
/* 512MiB is large enough for testing purposes */
static const unsigned int kSizeVirtualDisk = 536870912;
@@ -79,28 +100,31 @@
static const unsigned int kMajorBlockExperimentalMin = 240;
static const unsigned int kMajorBlockExperimentalMax = 254;
-VolumeManager *VolumeManager::sInstance = NULL;
+VolumeManager* VolumeManager::sInstance = NULL;
-VolumeManager *VolumeManager::Instance() {
- if (!sInstance)
- sInstance = new VolumeManager();
+VolumeManager* VolumeManager::Instance() {
+ if (!sInstance) sInstance = new VolumeManager();
return sInstance;
}
VolumeManager::VolumeManager() {
mDebug = false;
mNextObbId = 0;
+ mNextStubVolumeId = 0;
// For security reasons, assume that a secure keyguard is
// showing until we hear otherwise
mSecureKeyguardShowing = true;
}
-VolumeManager::~VolumeManager() {
+VolumeManager::~VolumeManager() {}
+
+static bool hasIsolatedStorage() {
+ return GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, true));
}
int VolumeManager::updateVirtualDisk() {
ATRACE_NAME("VolumeManager::updateVirtualDisk");
- if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
+ if (GetBoolProperty(kPropVirtualDisk, false)) {
if (access(kPathVirtualDisk, F_OK) != 0) {
Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
}
@@ -117,8 +141,9 @@
return -1;
}
- auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
- android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
+ auto disk = new android::vold::Disk(
+ "virtual", buf.st_rdev, "virtual",
+ android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
handleDiskAdded(mVirtualDisk);
}
@@ -157,7 +182,7 @@
// storage; the framework will decide if it should be mounted.
CHECK(mInternalEmulated == nullptr);
mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
- new android::vold::EmulatedVolume("/data/media"));
+ new android::vold::EmulatedVolume("/data/media"));
mInternalEmulated->create();
// Consider creating a virtual disk
@@ -173,17 +198,17 @@
return 0;
}
-void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
+void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
std::lock_guard<std::mutex> lock(mLock);
if (mDebug) {
- LOG(VERBOSE) << "----------------";
- LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
+ LOG(DEBUG) << "----------------";
+ LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
evt->dump();
}
- std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
- std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
+ std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
+ std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
if (devType != "disk") return;
@@ -192,43 +217,42 @@
dev_t device = makedev(major, minor);
switch (evt->getAction()) {
- case NetlinkEvent::Action::kAdd: {
- for (const auto& source : mDiskSources) {
- if (source->matches(eventPath)) {
- // For now, assume that MMC and virtio-blk (the latter is
- // emulator-specific; see Disk.cpp for details) devices are SD,
- // and that everything else is USB
- int flags = source->getFlags();
- if (major == kMajorBlockMmc
- || (android::vold::IsRunningInEmulator()
- && major >= (int) kMajorBlockExperimentalMin
- && major <= (int) kMajorBlockExperimentalMax)) {
- flags |= android::vold::Disk::Flags::kSd;
- } else {
- flags |= android::vold::Disk::Flags::kUsb;
- }
+ case NetlinkEvent::Action::kAdd: {
+ for (const auto& source : mDiskSources) {
+ if (source->matches(eventPath)) {
+ // For now, assume that MMC and virtio-blk (the latter is
+ // emulator-specific; see Disk.cpp for details) devices are SD,
+ // and that everything else is USB
+ int flags = source->getFlags();
+ if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
+ major >= (int)kMajorBlockExperimentalMin &&
+ major <= (int)kMajorBlockExperimentalMax)) {
+ flags |= android::vold::Disk::Flags::kSd;
+ } else {
+ flags |= android::vold::Disk::Flags::kUsb;
+ }
- auto disk = new android::vold::Disk(eventPath, device,
- source->getNickname(), flags);
- handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
- break;
+ auto disk =
+ new android::vold::Disk(eventPath, device, source->getNickname(), flags);
+ handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
+ break;
+ }
}
+ break;
}
- break;
- }
- case NetlinkEvent::Action::kChange: {
- LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
- handleDiskChanged(device);
- break;
- }
- case NetlinkEvent::Action::kRemove: {
- handleDiskRemoved(device);
- break;
- }
- default: {
- LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
- break;
- }
+ case NetlinkEvent::Action::kChange: {
+ LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
+ handleDiskChanged(device);
+ break;
+ }
+ case NetlinkEvent::Action::kRemove: {
+ handleDiskRemoved(device);
+ break;
+ }
+ default: {
+ LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
+ break;
+ }
}
}
@@ -237,7 +261,7 @@
// until the user unlocks the device to actually touch it
if (mSecureKeyguardShowing) {
LOG(INFO) << "Found disk at " << disk->getEventPath()
- << " but delaying scan due to secure keyguard";
+ << " but delaying scan due to secure keyguard";
mPendingDisks.push_back(disk);
} else {
disk->create();
@@ -304,6 +328,11 @@
return vol;
}
}
+ for (const auto& vol : mStubVolumes) {
+ if (vol->getId() == id) {
+ return vol;
+ }
+ }
for (const auto& vol : mObbVolumes) {
if (vol->getId() == id) {
return vol;
@@ -313,7 +342,7 @@
}
void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
- std::list<std::string>& list) {
+ std::list<std::string>& list) const {
list.clear();
for (const auto& disk : mDisks) {
disk->listVolumes(type, list);
@@ -333,8 +362,8 @@
LOG(ERROR) << "Failed to unlink " << keyPath;
success = false;
}
- if (e4crypt_is_native()) {
- if (!e4crypt_destroy_volume_keys(fsUuid)) {
+ if (fscrypt_is_native()) {
+ if (!fscrypt_destroy_volume_keys(fsUuid)) {
success = false;
}
}
@@ -343,25 +372,410 @@
int VolumeManager::linkPrimary(userid_t userId) {
std::string source(mPrimary->getPath());
- if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
+ if (mPrimary->isEmulated()) {
source = StringPrintf("%s/%d", source.c_str(), userId);
fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
}
std::string target(StringPrintf("/mnt/user/%d/primary", userId));
- if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
- if (errno != ENOENT) {
- PLOG(WARNING) << "Failed to unlink " << target;
+ LOG(DEBUG) << "Linking " << source << " to " << target;
+ Symlink(source, target);
+ return 0;
+}
+
+int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
+ const std::string& mntTargetRoot,
+ const std::string& packageName, const char* dirName) {
+ std::string mntSourceDir =
+ StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
+ if (CreateDir(mntSourceDir, 0755) < 0) {
+ return -errno;
+ }
+ std::string mntTargetDir =
+ StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
+ if (CreateDir(mntTargetDir, 0755) < 0) {
+ return -errno;
+ }
+ return BindMount(mntSourceDir, mntTargetDir);
+}
+
+int VolumeManager::mountPkgSpecificDirsForRunningProcs(
+ userid_t userId, const std::vector<std::string>& packageNames,
+ const std::vector<std::string>& visibleVolLabels, int remountMode) {
+ std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
+ if (!dirp) {
+ PLOG(ERROR) << "Failed to opendir /proc";
+ return -1;
+ }
+
+ std::string rootName;
+ // Figure out root namespace to compare against below
+ if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
+ PLOG(ERROR) << "Failed to read root namespace";
+ return -1;
+ }
+
+ struct stat mntFullSb;
+ struct stat mntWriteSb;
+ if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/full", &mntFullSb)) == -1) {
+ PLOG(ERROR) << "Failed to stat /mnt/runtime/full";
+ return -1;
+ }
+ if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &mntWriteSb)) == -1) {
+ PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
+ return -1;
+ }
+
+ std::string obbMountDir = StringPrintf("/mnt/user/%d/obb_mount", userId);
+ if (fs_prepare_dir(obbMountDir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
+ PLOG(ERROR) << "Failed to fs_prepare_dir " << obbMountDir;
+ return -1;
+ }
+ const unique_fd obbMountDirFd(
+ TEMP_FAILURE_RETRY(open(obbMountDir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)));
+ if (obbMountDirFd.get() < 0) {
+ PLOG(ERROR) << "Failed to open " << obbMountDir;
+ return -1;
+ }
+
+ std::unordered_set<appid_t> validAppIds;
+ for (auto& package : packageNames) {
+ validAppIds.insert(mAppIds[package]);
+ }
+ std::vector<std::string>& userPackages = mUserPackages[userId];
+
+ std::vector<pid_t> childPids;
+
+ struct dirent* de;
+ // Poke through all running PIDs look for apps running in userId
+ while ((de = readdir(dirp.get()))) {
+ pid_t pid;
+ if (de->d_type != DT_DIR) continue;
+ if (!android::base::ParseInt(de->d_name, &pid)) continue;
+
+ const unique_fd pidFd(
+ openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+ if (pidFd.get() < 0) {
+ PLOG(WARNING) << "Failed to open /proc/" << pid;
+ continue;
+ }
+ struct stat sb;
+ if (fstat(pidFd.get(), &sb) != 0) {
+ PLOG(WARNING) << "Failed to stat " << de->d_name;
+ continue;
+ }
+ if (multiuser_get_user_id(sb.st_uid) != userId) {
+ continue;
+ }
+
+ // Matches so far, but refuse to touch if in root namespace
+ LOG(VERBOSE) << "Found matching PID " << de->d_name;
+ std::string pidName;
+ if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
+ PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
+ continue;
+ }
+ if (rootName == pidName) {
+ LOG(WARNING) << "Skipping due to root namespace";
+ continue;
+ }
+
+ // Only update the mount points of processes running with one of validAppIds.
+ // This should skip any isolated uids.
+ appid_t appId = multiuser_get_app_id(sb.st_uid);
+ if (validAppIds.find(appId) == validAppIds.end()) {
+ continue;
+ }
+
+ std::vector<std::string> packagesForUid;
+ for (auto& package : userPackages) {
+ if (mAppIds[package] == appId) {
+ packagesForUid.push_back(package);
+ }
+ }
+ if (packagesForUid.empty()) {
+ continue;
+ }
+ const std::string& sandboxId = mSandboxIds[appId];
+
+ // We purposefully leave the namespace open across the fork
+ // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
+ unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY));
+ if (nsFd.get() < 0) {
+ PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
+ continue;
+ }
+
+ pid_t child;
+ if (!(child = fork())) {
+ if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
+ PLOG(ERROR) << "Failed to setns for " << de->d_name;
+ _exit(1);
+ }
+
+ int mountMode;
+ if (remountMode == -1) {
+ mountMode =
+ getMountModeForRunningProc(packagesForUid, userId, mntWriteSb, mntFullSb);
+ if (mountMode == -1) {
+ _exit(1);
+ }
+ } else {
+ mountMode = remountMode;
+ if (handleMountModeInstaller(mountMode, obbMountDirFd.get(), obbMountDir,
+ sandboxId) < 0) {
+ _exit(1);
+ }
+ }
+ if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
+ mountMode == VoldNativeService::REMOUNT_MODE_LEGACY ||
+ mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
+ // These mount modes are not going to change dynamically, so don't bother
+ // unmounting/remounting dirs.
+ _exit(0);
+ }
+
+ for (auto& volumeLabel : visibleVolLabels) {
+ std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
+ std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
+ if (volumeLabel == "emulated") {
+ StringAppendF(&mntSource, "/%d", userId);
+ StringAppendF(&mntTarget, "/%d", userId);
+ }
+
+ std::string sandboxSource =
+ StringPrintf("%s/Android/sandbox/%s", mntSource.c_str(), sandboxId.c_str());
+ if (CreateDir(sandboxSource, 0755) < 0) {
+ continue;
+ }
+ if (BindMount(sandboxSource, mntTarget) < 0) {
+ continue;
+ }
+
+ std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
+ std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
+ if (UnmountTree(obbTargetDir) < 0) {
+ continue;
+ }
+ if (!createPkgSpecificDirRoots(mntSource) || !createPkgSpecificDirRoots(mntTarget)) {
+ continue;
+ }
+ for (auto& package : packagesForUid) {
+ mountPkgSpecificDir(mntSource, mntTarget, package, "data");
+ mountPkgSpecificDir(mntSource, mntTarget, package, "media");
+ if (mountMode != VoldNativeService::REMOUNT_MODE_INSTALLER) {
+ mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
+ }
+ }
+ if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
+ if (BindMount(obbSourceDir, obbTargetDir) < 0) {
+ continue;
+ }
+ }
+ }
+ _exit(0);
+ }
+
+ if (child == -1) {
+ PLOG(ERROR) << "Failed to fork";
+ } else {
+ childPids.push_back(child);
}
}
- LOG(DEBUG) << "Linking " << source << " to " << target;
- if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
- PLOG(WARNING) << "Failed to link";
+ for (auto& child : childPids) {
+ TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
+ }
+ return 0;
+}
+
+int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
+ userid_t userId, struct stat& mntWriteStat,
+ struct stat& mntFullStat) {
+ struct stat storageSb;
+ if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
+ PLOG(ERROR) << "Failed to stat /storage";
+ return -1;
+ }
+
+ // Some packages have access to full external storage, identify processes belonging
+ // to those packages by comparing inode no.s of /mnt/runtime/full and /storage
+ if (storageSb.st_dev == mntFullStat.st_dev && storageSb.st_ino == mntFullStat.st_ino) {
+ return VoldNativeService::REMOUNT_MODE_FULL;
+ } else if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
+ return VoldNativeService::REMOUNT_MODE_LEGACY;
+ }
+
+ std::string obbMountFile =
+ StringPrintf("/mnt/user/%d/obb_mount/%s", userId, packagesForUid[0].c_str());
+ if (TEMP_FAILURE_RETRY(access(obbMountFile.c_str(), F_OK)) != -1) {
+ return VoldNativeService::REMOUNT_MODE_INSTALLER;
+ } else if (errno != ENOENT) {
+ PLOG(ERROR) << "Failed to access " << obbMountFile;
+ return -1;
+ }
+
+ // Some packages don't have access to external storage and processes belonging to
+ // those packages don't have anything mounted at /storage. So, identify those
+ // processes by comparing inode no.s of /mnt/user/%d/package
+ // and /storage
+ std::string sandbox = StringPrintf("/mnt/user/%d/package", userId);
+ struct stat sandboxStat;
+ if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
+ PLOG(ERROR) << "Failed to stat " << sandbox;
+ return -1;
+ }
+ if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
+ return VoldNativeService::REMOUNT_MODE_WRITE;
+ }
+
+ return VoldNativeService::REMOUNT_MODE_NONE;
+}
+
+int VolumeManager::handleMountModeInstaller(int mountMode, int obbMountDirFd,
+ const std::string& obbMountDir,
+ const std::string& sandboxId) {
+ if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
+ if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
+ return 0;
+ } else if (errno != ENOENT) {
+ PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
+ return -errno;
+ }
+ const unique_fd fd(TEMP_FAILURE_RETRY(
+ openat(obbMountDirFd, sandboxId.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
+ if (fd.get() < 0) {
+ PLOG(ERROR) << "Failed to create " << obbMountDir << "/" << sandboxId;
+ return -errno;
+ }
+ } else {
+ if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
+ if (TEMP_FAILURE_RETRY(unlinkat(obbMountDirFd, sandboxId.c_str(), 0)) == -1) {
+ PLOG(ERROR) << "Failed to unlink " << obbMountDir << "/" << sandboxId;
+ return -errno;
+ }
+ } else if (errno != ENOENT) {
+ PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
+ return -errno;
+ }
+ }
+ return 0;
+}
+
+int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
+ const std::vector<std::string>& visibleVolLabels) {
+ if (visibleVolLabels.empty()) {
+ return 0;
+ }
+ for (auto& volumeLabel : visibleVolLabels) {
+ std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
+ bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
+ if (isVolPrimaryEmulated) {
+ StringAppendF(&volumeRoot, "/%d", userId);
+ if (CreateDir(volumeRoot, 0755) < 0) {
+ return -errno;
+ }
+ }
+
+ std::string sandboxRoot =
+ prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
+ if (sandboxRoot.empty()) {
+ return -errno;
+ }
+ }
+
+ if (prepareSandboxTargets(userId, visibleVolLabels) < 0) {
+ return -errno;
+ }
+
+ if (mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1) < 0) {
+ PLOG(ERROR) << "Failed to setup sandboxes for already running processes";
return -errno;
}
return 0;
}
+int VolumeManager::prepareSandboxTargets(userid_t userId,
+ const std::vector<std::string>& visibleVolLabels) {
+ std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
+ if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
+ PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
+ return -errno;
+ }
+
+ StringAppendF(&mntTargetRoot, "/package");
+ if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
+ PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
+ return -errno;
+ }
+
+ for (auto& volumeLabel : visibleVolLabels) {
+ std::string sandboxTarget =
+ StringPrintf("%s/%s", mntTargetRoot.c_str(), volumeLabel.c_str());
+ if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
+ PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
+ return -errno;
+ }
+
+ if (mPrimary && volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
+ StringAppendF(&sandboxTarget, "/%d", userId);
+ if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
+ PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
+ return -errno;
+ }
+ }
+ }
+
+ StringAppendF(&mntTargetRoot, "/self");
+ if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
+ PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
+ return -errno;
+ }
+
+ if (mPrimary) {
+ std::string pkgPrimarySource(mPrimary->getPath());
+ if (mPrimary->isEmulated()) {
+ StringAppendF(&pkgPrimarySource, "/%d", userId);
+ }
+ StringAppendF(&mntTargetRoot, "/primary");
+ if (Symlink(pkgPrimarySource, mntTargetRoot) < 0) {
+ return -errno;
+ }
+ }
+ return 0;
+}
+
+std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
+ mode_t mode, uid_t uid, gid_t gid) {
+ std::string path(pathPrefix);
+ std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
+ for (size_t i = 0; i < subDirList.size(); ++i) {
+ std::string subDir = subDirList[i];
+ if (subDir.empty()) {
+ continue;
+ }
+ StringAppendF(&path, "/%s", subDir.c_str());
+ if (CreateDir(path, mode) < 0) {
+ return kEmptyString;
+ }
+ }
+ return path;
+}
+
+bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
+ std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
+ if (CreateDir(volumeAndroidRoot, 0700) < 0) {
+ return false;
+ }
+ std::array<std::string, 3> dirs = {"data", "media", "obb"};
+ for (auto& dir : dirs) {
+ std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
+ if (CreateDir(path, 0700) < 0) {
+ return false;
+ }
+ }
+ return true;
+}
+
int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
mAddedUsers[userId] = userSerialNumber;
return 0;
@@ -372,7 +786,10 @@
return 0;
}
-int VolumeManager::onUserStarted(userid_t userId) {
+int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
+ const std::vector<int>& appIds,
+ const std::vector<std::string>& sandboxIds) {
+ LOG(VERBOSE) << "onUserStarted: " << userId;
// Note that sometimes the system will spin up processes from Zygote
// before actually starting the user, so we're okay if Zygote
// already created this directory.
@@ -380,14 +797,159 @@
fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
mStartedUsers.insert(userId);
+ mUserPackages[userId] = packageNames;
+ for (size_t i = 0; i < packageNames.size(); ++i) {
+ mAppIds[packageNames[i]] = appIds[i];
+ mSandboxIds[appIds[i]] = sandboxIds[i];
+ }
if (mPrimary) {
linkPrimary(userId);
}
+ if (hasIsolatedStorage()) {
+ std::vector<std::string> visibleVolLabels;
+ for (auto& volId : mVisibleVolumeIds) {
+ auto vol = findVolume(volId);
+ userid_t mountUserId = vol->getMountUserId();
+ if (mountUserId == userId || vol->isEmulated()) {
+ visibleVolLabels.push_back(vol->getLabel());
+ }
+ }
+ if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
+ return -errno;
+ }
+ }
return 0;
}
int VolumeManager::onUserStopped(userid_t userId) {
+ LOG(VERBOSE) << "onUserStopped: " << userId;
mStartedUsers.erase(userId);
+
+ if (hasIsolatedStorage()) {
+ auto& userPackages = mUserPackages[userId];
+ std::string userMntTargetRoot = StringPrintf("/mnt/user/%d", userId);
+ std::string pkgPrimaryDir =
+ StringPrintf("%s/package/self/primary", userMntTargetRoot.c_str());
+ if (Unlink(pkgPrimaryDir) < 0) {
+ return -errno;
+ }
+ mUserPackages.erase(userId);
+ if (DeleteDirContentsAndDir(userMntTargetRoot) < 0) {
+ PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << userMntTargetRoot;
+ return -errno;
+ }
+ LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << userMntTargetRoot;
+ }
+ return 0;
+}
+
+int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
+ const std::vector<int32_t>& appIds) {
+ for (size_t i = 0; i < packageNames.size(); ++i) {
+ mAppIds[packageNames[i]] = appIds[i];
+ }
+ return 0;
+}
+
+int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
+ const std::vector<std::string>& sandboxIds) {
+ for (size_t i = 0; i < appIds.size(); ++i) {
+ mSandboxIds[appIds[i]] = sandboxIds[i];
+ }
+ return 0;
+}
+
+int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
+ const std::string& sandboxId, userid_t userId) {
+ if (!hasIsolatedStorage()) {
+ return 0;
+ } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
+ // User not started, no need to do anything now. Required bind mounts for the package will
+ // be created when the user starts.
+ return 0;
+ }
+
+ auto& userPackages = mUserPackages[userId];
+ if (std::find(userPackages.begin(), userPackages.end(), packageName) != userPackages.end()) {
+ return 0;
+ }
+
+ LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
+ << ", sandboxId=" << sandboxId << ", userId=" << userId;
+ mUserPackages[userId].push_back(packageName);
+ mAppIds[packageName] = appId;
+ mSandboxIds[appId] = sandboxId;
+
+ std::vector<std::string> visibleVolLabels;
+ for (auto& volId : mVisibleVolumeIds) {
+ auto vol = findVolume(volId);
+ userid_t mountUserId = vol->getMountUserId();
+ if (mountUserId == userId || vol->isEmulated()) {
+ visibleVolLabels.push_back(vol->getLabel());
+ }
+ }
+ return prepareSandboxes(userId, {packageName}, visibleVolLabels);
+}
+
+int VolumeManager::destroySandboxForApp(const std::string& packageName,
+ const std::string& sandboxId, userid_t userId) {
+ if (!hasIsolatedStorage()) {
+ return 0;
+ }
+ LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
+ << ", userId=" << userId;
+ auto& userPackages = mUserPackages[userId];
+ userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
+ userPackages.end());
+ // If the package is not uninstalled in any other users, remove appId and sandboxId
+ // corresponding to it from the internal state.
+ bool installedInAnyUser = false;
+ for (auto& it : mUserPackages) {
+ auto& packages = it.second;
+ if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
+ installedInAnyUser = true;
+ break;
+ }
+ }
+ if (!installedInAnyUser) {
+ const auto& entry = mAppIds.find(packageName);
+ if (entry != mAppIds.end()) {
+ mSandboxIds.erase(entry->second);
+ mAppIds.erase(entry);
+ }
+ }
+
+ std::vector<std::string> visibleVolLabels;
+ for (auto& volId : mVisibleVolumeIds) {
+ auto vol = findVolume(volId);
+ userid_t mountUserId = vol->getMountUserId();
+ if (mountUserId == userId || vol->isEmulated()) {
+ if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
+ return -errno;
+ }
+ }
+ }
+
+ return 0;
+}
+
+int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
+ const std::string& sandboxId, userid_t userId,
+ const std::string& volLabel) {
+ LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
+ << ", volLabel=" << volLabel;
+
+ std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
+ if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
+ StringAppendF(&sandboxDir, "/%d", userId);
+ }
+ StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
+
+ if (DeleteDirContentsAndDir(sandboxDir) < 0) {
+ PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
+ return -errno;
+ }
+
return 0;
}
@@ -405,7 +967,86 @@
return 0;
}
+int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
+ if (!hasIsolatedStorage()) {
+ return 0;
+ }
+
+ if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
+ return 0;
+ }
+
+ mVisibleVolumeIds.insert(vol->getId());
+ userid_t mountUserId = vol->getMountUserId();
+ if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
+ // We don't want to create another shared_ptr here because then we will end up with
+ // two shared_ptrs owning the underlying pointer without sharing it.
+ mPrimary = findVolume(vol->getId());
+ for (userid_t userId : mStartedUsers) {
+ if (linkPrimary(userId) != 0) {
+ return -errno;
+ }
+ }
+ }
+ if (vol->isEmulated()) {
+ for (userid_t userId : mStartedUsers) {
+ if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
+ return -errno;
+ }
+ }
+ } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
+ if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
+ return -errno;
+ }
+ }
+ return 0;
+}
+
+int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
+ if (!hasIsolatedStorage()) {
+ return 0;
+ }
+
+ if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
+ return 0;
+ }
+
+ if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
+ mPrimary = nullptr;
+ }
+
+ LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
+ userid_t mountUserId = vol->getMountUserId();
+ if (vol->isEmulated()) {
+ for (userid_t userId : mStartedUsers) {
+ if (destroySandboxesForVol(vol, userId) != 0) {
+ return -errno;
+ }
+ }
+ } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
+ if (destroySandboxesForVol(vol, mountUserId) != 0) {
+ return -errno;
+ }
+ }
+ return 0;
+}
+
+int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
+ LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
+ std::string volSandboxRoot =
+ StringPrintf("/mnt/user/%d/package/%s", userId, vol->getLabel().c_str());
+ if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
+ PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
+ return -errno;
+ }
+ LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
+ return 0;
+}
+
int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
+ if (hasIsolatedStorage()) {
+ return 0;
+ }
mPrimary = vol;
for (userid_t userId : mStartedUsers) {
linkPrimary(userId);
@@ -413,34 +1054,56 @@
return 0;
}
-static int unmount_tree(const std::string& prefix) {
- FILE* fp = setmntent("/proc/mounts", "r");
- if (fp == NULL) {
- PLOG(ERROR) << "Failed to open /proc/mounts";
- return -errno;
+int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
+ if (!hasIsolatedStorage()) {
+ return remountUidLegacy(uid, mountMode);
}
- // Some volumes can be stacked on each other, so force unmount in
- // reverse order to give us the best chance of success.
- std::list<std::string> toUnmount;
- mntent* mentry;
- while ((mentry = getmntent(fp)) != NULL) {
- auto test = std::string(mentry->mnt_dir) + "/";
- if (android::base::StartsWith(test, prefix)) {
- toUnmount.push_front(test);
+ appid_t appId = multiuser_get_app_id(uid);
+ userid_t userId = multiuser_get_user_id(uid);
+ std::vector<std::string> visibleVolLabels;
+ for (auto& volId : mVisibleVolumeIds) {
+ auto vol = findVolume(volId);
+ userid_t mountUserId = vol->getMountUserId();
+ if (mountUserId == userId || vol->isEmulated()) {
+ visibleVolLabels.push_back(vol->getLabel());
}
}
- endmntent(fp);
- for (const auto& path : toUnmount) {
- if (umount2(path.c_str(), MNT_DETACH)) {
- PLOG(ERROR) << "Failed to unmount " << path;
+ // Finding one package with appId is enough
+ std::vector<std::string> packageNames;
+ for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
+ if (it->second == appId) {
+ packageNames.push_back(it->first);
+ break;
}
}
- return 0;
+ if (packageNames.empty()) {
+ PLOG(ERROR) << "Failed to find packageName for " << uid;
+ return -1;
+ }
+ return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
}
-int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
+int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
+ std::string mode;
+ switch (mountMode) {
+ case VoldNativeService::REMOUNT_MODE_NONE:
+ mode = "none";
+ break;
+ case VoldNativeService::REMOUNT_MODE_DEFAULT:
+ mode = "default";
+ break;
+ case VoldNativeService::REMOUNT_MODE_READ:
+ mode = "read";
+ break;
+ case VoldNativeService::REMOUNT_MODE_WRITE:
+ mode = "write";
+ break;
+ default:
+ PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
+ return -1;
+ }
LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
DIR* dir;
@@ -452,6 +1115,8 @@
struct stat sb;
pid_t child;
+ static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
+
if (!(dir = opendir("/proc"))) {
PLOG(ERROR) << "Failed to opendir";
return -1;
@@ -496,8 +1161,29 @@
goto next;
}
+ if (apexUpdatable) {
+ std::string exeName;
+ // When ro.apex.bionic_updatable is set to true,
+ // some early native processes have mount namespaces that are different
+ // from that of the init. Therefore, above check can't filter them out.
+ // Since the propagation type of / is 'shared', unmounting /storage
+ // for the early native processes affects other processes including
+ // init. Filter out such processes by skipping if a process is a
+ // non-Java process whose UID is < AID_APP_START. (The UID condition
+ // is required to not filter out child processes spawned by apps.)
+ if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
+ PLOG(WARNING) << "Failed to read exe name for " << de->d_name;
+ goto next;
+ }
+ if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
+ LOG(WARNING) << "Skipping due to native system process";
+ goto next;
+ }
+ }
+
// We purposefully leave the namespace open across the fork
- nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
+ // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
+ nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
if (nsFd < 0) {
PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
goto next;
@@ -509,7 +1195,7 @@
_exit(1);
}
- unmount_tree("/storage/");
+ android::vold::UnmountTree("/storage/");
std::string storageSource;
if (mode == "default") {
@@ -522,26 +1208,22 @@
// Sane default of no storage visible
_exit(0);
}
- if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
- NULL, MS_BIND | MS_REC, NULL)) == -1) {
- PLOG(ERROR) << "Failed to mount " << storageSource << " for "
- << de->d_name;
+ if (TEMP_FAILURE_RETRY(
+ mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
+ PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
_exit(1);
}
- if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
- MS_REC | MS_SLAVE, NULL)) == -1) {
- PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
- << de->d_name;
+ if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
+ PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
_exit(1);
}
// Mount user-specific symlink helper into place
userid_t user_id = multiuser_get_user_id(uid);
std::string userSource(StringPrintf("/mnt/user/%d", user_id));
- if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
- NULL, MS_BIND, NULL)) == -1) {
- PLOG(ERROR) << "Failed to mount " << userSource << " for "
- << de->d_name;
+ if (TEMP_FAILURE_RETRY(
+ mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
+ PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
_exit(1);
}
@@ -555,7 +1237,7 @@
TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
}
-next:
+ next:
close(nsFd);
close(pidFd);
}
@@ -576,6 +1258,15 @@
}
updateVirtualDisk();
mAddedUsers.clear();
+
+ mUserPackages.clear();
+ mAppIds.clear();
+ mSandboxIds.clear();
+ mVisibleVolumeIds.clear();
+
+ for (userid_t userId : mStartedUsers) {
+ DeleteDirContents(StringPrintf("/mnt/user/%d/package", userId));
+ }
mStartedUsers.clear();
return 0;
}
@@ -583,7 +1274,7 @@
// Can be called twice (sequentially) during shutdown. should be safe for that.
int VolumeManager::shutdown() {
if (mInternalEmulated == nullptr) {
- return 0; // already shutdown
+ return 0; // already shutdown
}
android::vold::sSleepOnUnmount = false;
mInternalEmulated->destroy();
@@ -591,6 +1282,7 @@
for (const auto& disk : mDisks) {
disk->destroy();
}
+ mStubVolumes.clear();
mDisks.clear();
mPendingDisks.clear();
android::vold::sSleepOnUnmount = true;
@@ -605,13 +1297,16 @@
if (mInternalEmulated != nullptr) {
mInternalEmulated->unmount();
}
+ for (const auto& stub : mStubVolumes) {
+ stub->unmount();
+ }
for (const auto& disk : mDisks) {
disk->unmountAll();
}
// Worst case we might have some stale mounts lurking around, so
// force unmount those just to be safe.
- FILE* fp = setmntent("/proc/mounts", "r");
+ FILE* fp = setmntent("/proc/mounts", "re");
if (fp == NULL) {
PLOG(ERROR) << "Failed to open /proc/mounts";
return -errno;
@@ -623,9 +1318,12 @@
mntent* mentry;
while ((mentry = getmntent(fp)) != NULL) {
auto test = std::string(mentry->mnt_dir);
- if ((android::base::StartsWith(test, "/mnt/") &&
- !android::base::StartsWith(test, "/mnt/vendor")) ||
- android::base::StartsWith(test, "/storage/")) {
+ if ((StartsWith(test, "/mnt/") &&
+#ifdef __ANDROID_DEBUGGABLE__
+ !StartsWith(test, "/mnt/scratch") &&
+#endif
+ !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
+ StartsWith(test, "/storage/")) {
toUnmount.push_front(test);
}
}
@@ -641,7 +1339,7 @@
int VolumeManager::mkdirs(const std::string& path) {
// Only offer to create directories for paths managed by vold
- if (android::base::StartsWith(path, "/storage/")) {
+ if (StartsWith(path, "/storage/")) {
// fs_mkdirs() does symlink checking and relative path enforcement
return fs_mkdirs(path.c_str(), 0700);
} else {
@@ -650,157 +1348,12 @@
}
}
-static size_t kAppFuseMaxMountPointName = 32;
-
-static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
- if (name.size() > kAppFuseMaxMountPointName) {
- LOG(ERROR) << "AppFuse mount name is too long.";
- return -EINVAL;
- }
- for (size_t i = 0; i < name.size(); i++) {
- if (!isalnum(name[i])) {
- LOG(ERROR) << "AppFuse mount name contains invalid character.";
- return -EINVAL;
- }
- }
- *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
- return android::OK;
-}
-
-static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
- // Remove existing mount.
- android::vold::ForceUnmount(path);
-
- const auto opts = android::base::StringPrintf(
- "fd=%i,"
- "rootmode=40000,"
- "default_permissions,"
- "allow_other,"
- "user_id=%d,group_id=%d,"
- "context=\"u:object_r:app_fuse_file:s0\","
- "fscontext=u:object_r:app_fusefs:s0",
- device_fd,
- uid,
- uid);
-
- const int result = TEMP_FAILURE_RETRY(mount(
- "/dev/fuse", path.c_str(), "fuse",
- MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
- if (result != 0) {
- PLOG(ERROR) << "Failed to mount " << path;
- return -errno;
- }
-
- return android::OK;
-}
-
-static android::status_t runCommandInNamespace(const std::string& command,
- uid_t uid,
- pid_t pid,
- const std::string& path,
- int device_fd) {
- if (DEBUG_APPFUSE) {
- LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
- << " in namespace " << uid;
- }
-
- unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
- if (dir.get() == -1) {
- PLOG(ERROR) << "Failed to open /proc";
- return -errno;
- }
-
- // Obtains process file descriptor.
- const std::string pid_str = android::base::StringPrintf("%d", pid);
- const unique_fd pid_fd(
- openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
- if (pid_fd.get() == -1) {
- PLOG(ERROR) << "Failed to open /proc/" << pid;
- return -errno;
- }
-
- // Check UID of process.
- {
- struct stat sb;
- const int result = fstat(pid_fd.get(), &sb);
- if (result == -1) {
- PLOG(ERROR) << "Failed to stat /proc/" << pid;
- return -errno;
- }
- if (sb.st_uid != AID_SYSTEM) {
- LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
- << ", actual=" << sb.st_uid;
- return -EPERM;
- }
- }
-
- // Matches so far, but refuse to touch if in root namespace
- {
- std::string rootName;
- std::string pidName;
- if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
- || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
- PLOG(ERROR) << "Failed to read namespaces";
- return -EPERM;
- }
- if (rootName == pidName) {
- LOG(ERROR) << "Don't mount appfuse in root namespace";
- return -EPERM;
- }
- }
-
- // We purposefully leave the namespace open across the fork
- unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
- if (ns_fd.get() < 0) {
- PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
- return -errno;
- }
-
- int child = fork();
- if (child == 0) {
- if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
- PLOG(ERROR) << "Failed to setns";
- _exit(-errno);
- }
-
- if (command == "mount") {
- _exit(mountInNamespace(uid, device_fd, path));
- } else if (command == "unmount") {
- // If it's just after all FD opened on mount point are closed, umount2 can fail with
- // EBUSY. To avoid the case, specify MNT_DETACH.
- if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
- errno != EINVAL && errno != ENOENT) {
- PLOG(ERROR) << "Failed to unmount directory.";
- _exit(-errno);
- }
- if (rmdir(path.c_str()) != 0) {
- PLOG(ERROR) << "Failed to remove the mount directory.";
- _exit(-errno);
- }
- _exit(android::OK);
- } else {
- LOG(ERROR) << "Unknown appfuse command " << command;
- _exit(-EPERM);
- }
- }
-
- if (child == -1) {
- PLOG(ERROR) << "Failed to folk child process";
- return -errno;
- }
-
- android::status_t status;
- TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
-
- return status;
-}
-
int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
- int32_t ownerGid, std::string* outVolId) {
+ int32_t ownerGid, std::string* outVolId) {
int id = mNextObbId++;
auto vol = std::shared_ptr<android::vold::VolumeBase>(
- new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
+ new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
vol->create();
mObbVolumes.push_back(vol);
@@ -821,44 +1374,40 @@
return android::OK;
}
-int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
- android::base::unique_fd* device_fd) {
- std::string name = std::to_string(mountId);
+int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
+ const std::string& fsType, const std::string& fsUuid,
+ const std::string& fsLabel, std::string* outVolId) {
+ int id = mNextStubVolumeId++;
+ auto vol = std::shared_ptr<android::vold::VolumeBase>(
+ new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
+ vol->create();
- // Check mount point name.
- std::string path;
- if (getMountPath(uid, name, &path) != android::OK) {
- LOG(ERROR) << "Invalid mount point name";
- return -1;
- }
-
- // Create directories.
- const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
- if (result != android::OK) {
- PLOG(ERROR) << "Failed to prepare directory " << path;
- return -1;
- }
-
- // Open device FD.
- device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
- if (device_fd->get() == -1) {
- PLOG(ERROR) << "Failed to open /dev/fuse";
- return -1;
- }
-
- // Mount.
- return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
+ mStubVolumes.push_back(vol);
+ *outVolId = vol->getId();
+ return android::OK;
}
-int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
- std::string name = std::to_string(mountId);
-
- // Check mount point name.
- std::string path;
- if (getMountPath(uid, name, &path) != android::OK) {
- LOG(ERROR) << "Invalid mount point name";
- return -1;
+int VolumeManager::destroyStubVolume(const std::string& volId) {
+ auto i = mStubVolumes.begin();
+ while (i != mStubVolumes.end()) {
+ if ((*i)->getId() == volId) {
+ (*i)->destroy();
+ i = mStubVolumes.erase(i);
+ } else {
+ ++i;
+ }
}
+ return android::OK;
+}
- return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
+int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
+ return android::vold::MountAppFuse(uid, mountId, device_fd);
+}
+
+int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
+ return android::vold::UnmountAppFuse(uid, mountId);
+}
+
+int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
+ return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
}
diff --git a/VolumeManager.h b/VolumeManager.h
index fb455d8..bb93b13 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -17,8 +17,8 @@
#ifndef ANDROID_VOLD_VOLUME_MANAGER_H
#define ANDROID_VOLD_VOLUME_MANAGER_H
-#include <pthread.h>
#include <fnmatch.h>
+#include <pthread.h>
#include <stdlib.h>
#include <list>
@@ -29,24 +29,22 @@
#include <android-base/unique_fd.h>
#include <cutils/multiuser.h>
+#include <sysutils/NetlinkEvent.h>
#include <utils/List.h>
#include <utils/Timers.h>
-#include <sysutils/NetlinkEvent.h>
#include "android/os/IVoldListener.h"
#include "model/Disk.h"
#include "model/VolumeBase.h"
-#define DEBUG_APPFUSE 0
-
class VolumeManager {
-private:
- static VolumeManager *sInstance;
+ private:
+ static VolumeManager* sInstance;
- bool mDebug;
+ bool mDebug;
-public:
+ public:
virtual ~VolumeManager();
// TODO: pipe all requests through VM to avoid exposing this lock
@@ -54,27 +52,26 @@
std::mutex& getCryptLock() { return mCryptLock; }
void setListener(android::sp<android::os::IVoldListener> listener) { mListener = listener; }
- android::sp<android::os::IVoldListener> getListener() { return mListener; }
+ android::sp<android::os::IVoldListener> getListener() const { return mListener; }
int start();
int stop();
- void handleBlockEvent(NetlinkEvent *evt);
+ void handleBlockEvent(NetlinkEvent* evt);
class DiskSource {
- public:
- DiskSource(const std::string& sysPattern, const std::string& nickname, int flags) :
- mSysPattern(sysPattern), mNickname(nickname), mFlags(flags) {
- }
+ public:
+ DiskSource(const std::string& sysPattern, const std::string& nickname, int flags)
+ : mSysPattern(sysPattern), mNickname(nickname), mFlags(flags) {}
bool matches(const std::string& sysPath) {
return !fnmatch(mSysPattern.c_str(), sysPath.c_str(), 0);
}
- const std::string& getNickname() { return mNickname; }
- int getFlags() { return mFlags; }
+ const std::string& getNickname() const { return mNickname; }
+ int getFlags() const { return mFlags; }
- private:
+ private:
std::string mSysPattern;
std::string mNickname;
int mFlags;
@@ -85,20 +82,33 @@
std::shared_ptr<android::vold::Disk> findDisk(const std::string& id);
std::shared_ptr<android::vold::VolumeBase> findVolume(const std::string& id);
- void listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list);
+ void listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) const;
int forgetPartition(const std::string& partGuid, const std::string& fsUuid);
int onUserAdded(userid_t userId, int userSerialNumber);
int onUserRemoved(userid_t userId);
- int onUserStarted(userid_t userId);
+ int onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
+ const std::vector<int>& appIds, const std::vector<std::string>& sandboxIds);
int onUserStopped(userid_t userId);
+ int addAppIds(const std::vector<std::string>& packageNames, const std::vector<int32_t>& appIds);
+ int addSandboxIds(const std::vector<int32_t>& appIds,
+ const std::vector<std::string>& sandboxIds);
+ int prepareSandboxForApp(const std::string& packageName, appid_t appId,
+ const std::string& sandboxId, userid_t userId);
+ int destroySandboxForApp(const std::string& packageName, const std::string& sandboxId,
+ userid_t userId);
+
+ int onVolumeMounted(android::vold::VolumeBase* vol);
+ int onVolumeUnmounted(android::vold::VolumeBase* vol);
+
int onSecureKeyguardStateChanged(bool isShowing);
int setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol);
- int remountUid(uid_t uid, const std::string& mode);
+ int remountUid(uid_t uid, int32_t remountMode);
+ int remountUidLegacy(uid_t uid, int32_t remountMode);
/* Reset all internal state, typically during framework boot */
int reset();
@@ -110,7 +120,7 @@
int updateVirtualDisk();
int setDebug(bool enable);
- static VolumeManager *Instance();
+ static VolumeManager* Instance();
/*
* Ensure that all directories along given path exist, creating parent
@@ -122,18 +132,44 @@
int mkdirs(const std::string& path);
int createObb(const std::string& path, const std::string& key, int32_t ownerGid,
- std::string* outVolId);
+ std::string* outVolId);
int destroyObb(const std::string& volId);
- int mountAppFuse(uid_t uid, pid_t pid, int mountId, android::base::unique_fd* device_fd);
- int unmountAppFuse(uid_t uid, pid_t pid, int mountId);
+ int createStubVolume(const std::string& sourcePath, const std::string& mountPath,
+ const std::string& fsType, const std::string& fsUuid,
+ const std::string& fsLabel, std::string* outVolId);
+ int destroyStubVolume(const std::string& volId);
-private:
+ int mountAppFuse(uid_t uid, int mountId, android::base::unique_fd* device_fd);
+ int unmountAppFuse(uid_t uid, int mountId);
+ int openAppFuseFile(uid_t uid, int mountId, int fileId, int flags);
+
+ private:
VolumeManager();
void readInitialState();
int linkPrimary(userid_t userId);
+ int prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
+ const std::vector<std::string>& visibleVolLabels);
+ int prepareSandboxTargets(userid_t userId, const std::vector<std::string>& visibleVolLabels);
+ int handleMountModeInstaller(int mountMode, int obbMountDirFd, const std::string& obbMountDir,
+ const std::string& sandboxId);
+ int mountPkgSpecificDirsForRunningProcs(userid_t userId,
+ const std::vector<std::string>& packageNames,
+ const std::vector<std::string>& visibleVolLabels,
+ int remountMode);
+ int destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId);
+ std::string prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
+ mode_t mode, uid_t uid, gid_t gid);
+ bool createPkgSpecificDirRoots(const std::string& volumeRoot);
+ int mountPkgSpecificDir(const std::string& mntSourceRoot, const std::string& mntTargetRoot,
+ const std::string& packageName, const char* dirName);
+ int destroySandboxForAppOnVol(const std::string& packageName, const std::string& sandboxId,
+ userid_t userId, const std::string& volLabel);
+ int getMountModeForRunningProc(const std::vector<std::string>& packagesForUid, userid_t userId,
+ struct stat& mntWriteStat, struct stat& mntFullStat);
+
void handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk);
void handleDiskChanged(dev_t device);
void handleDiskRemoved(dev_t device);
@@ -147,6 +183,7 @@
std::list<std::shared_ptr<android::vold::Disk>> mDisks;
std::list<std::shared_ptr<android::vold::Disk>> mPendingDisks;
std::list<std::shared_ptr<android::vold::VolumeBase>> mObbVolumes;
+ std::list<std::shared_ptr<android::vold::VolumeBase>> mStubVolumes;
std::unordered_map<userid_t, int> mAddedUsers;
std::unordered_set<userid_t> mStartedUsers;
@@ -156,7 +193,13 @@
std::shared_ptr<android::vold::VolumeBase> mInternalEmulated;
std::shared_ptr<android::vold::VolumeBase> mPrimary;
+ std::unordered_map<std::string, appid_t> mAppIds;
+ std::unordered_map<appid_t, std::string> mSandboxIds;
+ std::unordered_map<userid_t, std::vector<std::string>> mUserPackages;
+ std::unordered_set<std::string> mVisibleVolumeIds;
+
int mNextObbId;
+ int mNextStubVolumeId;
bool mSecureKeyguardShowing;
};
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index 8300a8e..cc23498 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -29,9 +29,13 @@
void onUserAdded(int userId, int userSerial);
void onUserRemoved(int userId);
- void onUserStarted(int userId);
+ void onUserStarted(int userId, in @utf8InCpp String[] packageNames, in int[] appIds,
+ in @utf8InCpp String[] sandboxIds);
void onUserStopped(int userId);
+ void addAppIds(in @utf8InCpp String[] packageNames, in int[] appIds);
+ void addSandboxIds(in int[] appIds, in @utf8InCpp String[] sandboxIds);
+
void onSecureKeyguardStateChanged(boolean isShowing);
void partition(@utf8InCpp String diskId, int partitionType, int ratio);
@@ -44,22 +48,22 @@
void checkEncryption(@utf8InCpp String volId);
void moveStorage(@utf8InCpp String fromVolId, @utf8InCpp String toVolId,
- IVoldTaskListener listener);
+ IVoldTaskListener listener);
void remountUid(int uid, int remountMode);
void mkdirs(@utf8InCpp String path);
- @utf8InCpp String createObb(@utf8InCpp String sourcePath,
- @utf8InCpp String sourceKey, int ownerGid);
+ @utf8InCpp String createObb(@utf8InCpp String sourcePath, @utf8InCpp String sourceKey,
+ int ownerGid);
void destroyObb(@utf8InCpp String volId);
void fstrim(int fstrimFlags, IVoldTaskListener listener);
void runIdleMaint(IVoldTaskListener listener);
void abortIdleMaint(IVoldTaskListener listener);
- FileDescriptor mountAppFuse(int uid, int pid, int mountId);
- void unmountAppFuse(int uid, int pid, int mountId);
+ FileDescriptor mountAppFuse(int uid, int mountId);
+ void unmountAppFuse(int uid, int mountId);
void fdeCheckPassword(@utf8InCpp String password);
void fdeRestart();
@@ -84,15 +88,43 @@
void createUserKey(int userId, int userSerial, boolean ephemeral);
void destroyUserKey(int userId);
- void addUserKeyAuth(int userId, int userSerial, @utf8InCpp String token, @utf8InCpp String secret);
+ void addUserKeyAuth(int userId, int userSerial, @utf8InCpp String token,
+ @utf8InCpp String secret);
void fixateNewestUserKeyAuth(int userId);
- void unlockUserKey(int userId, int userSerial, @utf8InCpp String token, @utf8InCpp String secret);
+ void unlockUserKey(int userId, int userSerial, @utf8InCpp String token,
+ @utf8InCpp String secret);
void lockUserKey(int userId);
- void prepareUserStorage(@nullable @utf8InCpp String uuid, int userId, int userSerial, int storageFlags);
+ void prepareUserStorage(@nullable @utf8InCpp String uuid, int userId, int userSerial,
+ int storageFlags);
void destroyUserStorage(@nullable @utf8InCpp String uuid, int userId, int storageFlags);
+ void prepareSandboxForApp(in @utf8InCpp String packageName, int appId,
+ in @utf8InCpp String sandboxId, int userId);
+ void destroySandboxForApp(in @utf8InCpp String packageName,
+ in @utf8InCpp String sandboxId, int userId);
+
+ void startCheckpoint(int retry);
+ boolean needsCheckpoint();
+ boolean needsRollback();
+ void abortChanges(in @utf8InCpp String device, boolean retry);
+ void commitChanges();
+ void prepareCheckpoint();
+ void restoreCheckpoint(@utf8InCpp String device);
+ void restoreCheckpointPart(@utf8InCpp String device, int count);
+ void markBootAttempt();
+ boolean supportsCheckpoint();
+ boolean supportsBlockCheckpoint();
+ boolean supportsFileCheckpoint();
+
+ @utf8InCpp String createStubVolume(@utf8InCpp String sourcePath,
+ @utf8InCpp String mountPath, @utf8InCpp String fsType,
+ @utf8InCpp String fsUuid, @utf8InCpp String fsLabel);
+ void destroyStubVolume(@utf8InCpp String volId);
+
+ FileDescriptor openAppFuseFile(int uid, int mountId, int fileId, int flags);
+
const int ENCRYPTION_FLAG_NO_UI = 4;
const int ENCRYPTION_STATE_NONE = 1;
@@ -113,8 +145,8 @@
const int PASSWORD_TYPE_PASSWORD = 0;
const int PASSWORD_TYPE_DEFAULT = 1;
- const int PASSWORD_TYPE_PIN = 2;
- const int PASSWORD_TYPE_PATTERN = 3;
+ const int PASSWORD_TYPE_PATTERN = 2;
+ const int PASSWORD_TYPE_PIN = 3;
const int STORAGE_FLAG_DE = 1;
const int STORAGE_FLAG_CE = 2;
@@ -123,6 +155,9 @@
const int REMOUNT_MODE_DEFAULT = 1;
const int REMOUNT_MODE_READ = 2;
const int REMOUNT_MODE_WRITE = 3;
+ const int REMOUNT_MODE_LEGACY = 4;
+ const int REMOUNT_MODE_INSTALLER = 5;
+ const int REMOUNT_MODE_FULL = 6;
const int VOLUME_STATE_UNMOUNTED = 0;
const int VOLUME_STATE_CHECKING = 1;
@@ -139,4 +174,5 @@
const int VOLUME_TYPE_EMULATED = 2;
const int VOLUME_TYPE_ASEC = 3;
const int VOLUME_TYPE_OBB = 4;
+ const int VOLUME_TYPE_STUB = 5;
}
diff --git a/cryptfs.cpp b/cryptfs.cpp
index c5024ae..400a616 100644
--- a/cryptfs.cpp
+++ b/cryptfs.cpp
@@ -20,53 +20,66 @@
*
*/
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/stat.h>
-#include <ctype.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <sys/ioctl.h>
-#include <linux/dm-ioctl.h>
-#include <libgen.h>
-#include <stdlib.h>
-#include <sys/param.h>
-#include <string.h>
-#include <sys/mount.h>
+#define LOG_TAG "Cryptfs"
+
+#include "cryptfs.h"
+
+#include "Checkpoint.h"
+#include "EncryptInplace.h"
+#include "FsCrypt.h"
+#include "Keymaster.h"
+#include "Process.h"
+#include "ScryptParameters.h"
+#include "Utils.h"
+#include "VoldUtil.h"
+#include "VolumeManager.h"
+
+#include <android-base/parseint.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <bootloader_message/bootloader_message.h>
+#include <cutils/android_reboot.h>
+#include <cutils/properties.h>
+#include <ext4_utils/ext4_utils.h>
+#include <f2fs_sparseblock.h>
+#include <fs_mgr.h>
+#include <fscrypt/fscrypt.h>
+#include <hardware_legacy/power.h>
+#include <log/log.h>
+#include <logwrap/logwrap.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
-#include <errno.h>
-#include <ext4_utils/ext4_crypt.h>
-#include <ext4_utils/ext4_utils.h>
-#include <linux/kdev_t.h>
-#include <fs_mgr.h>
-#include <time.h>
-#include <math.h>
#include <selinux/selinux.h>
-#include "cryptfs.h"
-#include "secontext.h"
-#define LOG_TAG "Cryptfs"
-#include "cutils/log.h"
-#include "cutils/properties.h"
-#include "cutils/android_reboot.h"
-#include "hardware_legacy/power.h"
-#include <logwrap/logwrap.h>
-#include "ScryptParameters.h"
-#include "VolumeManager.h"
-#include "VoldUtil.h"
-#include "Ext4Crypt.h"
-#include "f2fs_sparseblock.h"
-#include "EncryptInplace.h"
-#include "Process.h"
-#include "Keymaster.h"
-#include "android-base/properties.h"
-#include <bootloader_message/bootloader_message.h>
+
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <libgen.h>
+#include <linux/dm-ioctl.h>
+#include <linux/kdev_t.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
extern "C" {
#include <crypto_scrypt.h>
}
+using android::base::ParseUint;
+using android::base::StringPrintf;
+using android::fs_mgr::GetEntryForMountPoint;
+using namespace std::chrono_literals;
+
#define UNUSED __attribute__((unused))
#define DM_CRYPT_BUF_SIZE 4096
@@ -75,14 +88,12 @@
constexpr size_t INTERMEDIATE_KEY_LEN_BYTES = 16;
constexpr size_t INTERMEDIATE_IV_LEN_BYTES = 16;
-constexpr size_t INTERMEDIATE_BUF_SIZE =
- (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
+constexpr size_t INTERMEDIATE_BUF_SIZE = (INTERMEDIATE_KEY_LEN_BYTES + INTERMEDIATE_IV_LEN_BYTES);
// SCRYPT_LEN is used by struct crypt_mnt_ftr for its intermediate key.
-static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN,
- "Mismatch of intermediate key sizes");
+static_assert(INTERMEDIATE_BUF_SIZE == SCRYPT_LEN, "Mismatch of intermediate key sizes");
-#define KEY_IN_FOOTER "footer"
+#define KEY_IN_FOOTER "footer"
#define DEFAULT_PASSWORD "default_password"
@@ -108,27 +119,25 @@
static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr);
static unsigned char saved_master_key[MAX_KEY_LEN];
-static char *saved_mount_point;
-static int master_key_saved = 0;
-static struct crypt_persist_data *persist_data = NULL;
+static char* saved_mount_point;
+static int master_key_saved = 0;
+static struct crypt_persist_data* persist_data = NULL;
/* Should we use keymaster? */
-static int keymaster_check_compatibility()
-{
+static int keymaster_check_compatibility() {
return keymaster_compatibility_cryptfs_scrypt();
}
/* Create a new keymaster key and store it in this footer */
-static int keymaster_create_key(struct crypt_mnt_ftr *ftr)
-{
+static int keymaster_create_key(struct crypt_mnt_ftr* ftr) {
if (ftr->keymaster_blob_size) {
SLOGI("Already have key");
return 0;
}
- int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
- KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
- &ftr->keymaster_blob_size);
+ int rc = keymaster_create_key_for_cryptfs_scrypt(
+ RSA_KEY_SIZE, RSA_EXPONENT, KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob,
+ KEYMASTER_BLOB_SIZE, &ftr->keymaster_blob_size);
if (rc) {
if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
SLOGE("Keymaster key blob too large");
@@ -141,12 +150,9 @@
}
/* This signs the given object using the keymaster key. */
-static int keymaster_sign_object(struct crypt_mnt_ftr *ftr,
- const unsigned char *object,
- const size_t object_size,
- unsigned char **signature,
- size_t *signature_size)
-{
+static int keymaster_sign_object(struct crypt_mnt_ftr* ftr, const unsigned char* object,
+ const size_t object_size, unsigned char** signature,
+ size_t* signature_size) {
unsigned char to_sign[RSA_KEY_SIZE_BYTES];
size_t to_sign_size = sizeof(to_sign);
memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
@@ -225,21 +231,20 @@
static int password_expiry_time = 0;
static const int password_max_age_seconds = 60;
-enum class RebootType {reboot, recovery, shutdown};
-static void cryptfs_reboot(RebootType rt)
-{
- switch (rt) {
- case RebootType::reboot:
- property_set(ANDROID_RB_PROPERTY, "reboot");
- break;
+enum class RebootType { reboot, recovery, shutdown };
+static void cryptfs_reboot(RebootType rt) {
+ switch (rt) {
+ case RebootType::reboot:
+ property_set(ANDROID_RB_PROPERTY, "reboot");
+ break;
- case RebootType::recovery:
- property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
- break;
+ case RebootType::recovery:
+ property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
+ break;
- case RebootType::shutdown:
- property_set(ANDROID_RB_PROPERTY, "shutdown");
- break;
+ case RebootType::shutdown:
+ property_set(ANDROID_RB_PROPERTY, "shutdown");
+ break;
}
sleep(20);
@@ -248,8 +253,7 @@
return;
}
-static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
-{
+static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
memset(io, 0, dataSize);
io->data_size = dataSize;
io->data_start = sizeof(struct dm_ioctl);
@@ -267,7 +271,7 @@
struct CryptoType;
// Use to get the CryptoType in use on this device.
-const CryptoType &get_crypto_type();
+const CryptoType& get_crypto_type();
struct CryptoType {
// We should only be constructing CryptoTypes as part of
@@ -279,60 +283,64 @@
constexpr CryptoType set_keysize(uint32_t size) const {
return CryptoType(this->property_name, this->crypto_name, size);
}
- constexpr CryptoType set_property_name(const char *property) const {
+ constexpr CryptoType set_property_name(const char* property) const {
return CryptoType(property, this->crypto_name, this->keysize);
}
- constexpr CryptoType set_crypto_name(const char *crypto) const {
+ constexpr CryptoType set_crypto_name(const char* crypto) const {
return CryptoType(this->property_name, crypto, this->keysize);
}
- constexpr const char *get_property_name() const { return property_name; }
- constexpr const char *get_crypto_name() const { return crypto_name; }
+ constexpr const char* get_property_name() const { return property_name; }
+ constexpr const char* get_crypto_name() const { return crypto_name; }
constexpr uint32_t get_keysize() const { return keysize; }
- private:
- const char *property_name;
- const char *crypto_name;
+ private:
+ const char* property_name;
+ const char* crypto_name;
uint32_t keysize;
- constexpr CryptoType(const char *property, const char *crypto,
- uint32_t ksize)
+ constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
: property_name(property), crypto_name(crypto), keysize(ksize) {}
- friend const CryptoType &get_crypto_type();
- static const CryptoType &get_device_crypto_algorithm();
+ friend const CryptoType& get_crypto_type();
+ static const CryptoType& get_device_crypto_algorithm();
};
// We only want to parse this read-only property once. But we need to wait
// until the system is initialized before we can read it. So we use a static
// scoped within this function to get it only once.
-const CryptoType &get_crypto_type() {
+const CryptoType& get_crypto_type() {
static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
return crypto_type;
}
constexpr CryptoType default_crypto_type = CryptoType()
- .set_property_name("AES-128-CBC")
- .set_crypto_name("aes-cbc-essiv:sha256")
- .set_keysize(16);
+ .set_property_name("AES-128-CBC")
+ .set_crypto_name("aes-cbc-essiv:sha256")
+ .set_keysize(16);
constexpr CryptoType supported_crypto_types[] = {
default_crypto_type,
+ CryptoType()
+ .set_property_name("adiantum")
+ .set_crypto_name("xchacha12,aes-adiantum-plain64")
+ .set_keysize(32),
// Add new CryptoTypes here. Order is not important.
};
-
// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
// We confirm all supported_crypto_types have a small enough keysize and
// had both set_property_name() and set_crypto_name() called.
template <typename T, size_t N>
-constexpr size_t array_length(T (&)[N]) { return N; }
+constexpr size_t array_length(T (&)[N]) {
+ return N;
+}
constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
return (index >= array_length(supported_crypto_types));
}
-constexpr bool isValidCryptoType(const CryptoType &crypto_type) {
+constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
return ((crypto_type.get_property_name() != nullptr) &&
(crypto_type.get_crypto_name() != nullptr) &&
(crypto_type.get_keysize() <= MAX_KEY_LEN));
@@ -343,8 +351,8 @@
// but it's asserting at compile time that all of our key lengths are valid.
constexpr bool validateSupportedCryptoTypes(size_t index) {
return indexOutOfBoundsForCryptoTypes(index) ||
- (isValidCryptoType(supported_crypto_types[index]) &&
- validateSupportedCryptoTypes(index + 1));
+ (isValidCryptoType(supported_crypto_types[index]) &&
+ validateSupportedCryptoTypes(index + 1));
}
static_assert(validateSupportedCryptoTypes(0),
@@ -352,34 +360,30 @@
"incompletely constructed.");
// ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
-
// Don't call this directly, use get_crypto_type(), which caches this result.
-const CryptoType &CryptoType::get_device_crypto_algorithm() {
+const CryptoType& CryptoType::get_device_crypto_algorithm() {
constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
char paramstr[PROPERTY_VALUE_MAX];
- property_get(CRYPT_ALGO_PROP, paramstr,
- default_crypto_type.get_property_name());
- for (auto const &ctype : supported_crypto_types) {
+ property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
+ for (auto const& ctype : supported_crypto_types) {
if (strcmp(paramstr, ctype.get_property_name()) == 0) {
return ctype;
}
}
- ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr,
- CRYPT_ALGO_PROP, default_crypto_type.get_property_name());
+ ALOGE("Invalid name (%s) for %s. Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
+ default_crypto_type.get_property_name());
return default_crypto_type;
}
} // namespace
-
-
/**
* Gets the default device scrypt parameters for key derivation time tuning.
* The parameters should lead to about one second derivation time for the
* given device.
*/
-static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
+static void get_device_scrypt_params(struct crypt_mnt_ftr* ftr) {
char paramstr[PROPERTY_VALUE_MAX];
int Nf, rf, pf;
@@ -397,17 +401,16 @@
return get_crypto_type().get_keysize();
}
-const char *cryptfs_get_crypto_name() {
+const char* cryptfs_get_crypto_name() {
return get_crypto_type().get_crypto_name();
}
-static unsigned int get_fs_size(char *dev)
-{
+static uint64_t get_fs_size(const char* dev) {
int fd, block_size;
struct ext4_super_block sb;
- off64_t len;
+ uint64_t len;
- if ((fd = open(dev, O_RDONLY|O_CLOEXEC)) < 0) {
+ if ((fd = open(dev, O_RDONLY | O_CLOEXEC)) < 0) {
SLOGE("Cannot open device to get filesystem size ");
return 0;
}
@@ -430,68 +433,75 @@
}
block_size = 1024 << sb.s_log_block_size;
/* compute length in bytes */
- len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
+ len = (((uint64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
/* return length in sectors */
- return (unsigned int) (len / 512);
+ return len / 512;
}
-static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
-{
- static int cached_data = 0;
- static off64_t cached_off = 0;
- static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
- int fd;
- char key_loc[PROPERTY_VALUE_MAX];
- char real_blkdev[PROPERTY_VALUE_MAX];
- int rc = -1;
-
- if (!cached_data) {
- fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
-
- if (!strcmp(key_loc, KEY_IN_FOOTER)) {
- if ( (fd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
- SLOGE("Cannot open real block device %s\n", real_blkdev);
- return -1;
- }
-
- unsigned long nr_sec = 0;
- get_blkdev_size(fd, &nr_sec);
- if (nr_sec != 0) {
- /* If it's an encrypted Android partition, the last 16 Kbytes contain the
- * encryption info footer and key, and plenty of bytes to spare for future
- * growth.
- */
- strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
- cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
- cached_data = 1;
- } else {
- SLOGE("Cannot get size of block device %s\n", real_blkdev);
- }
- close(fd);
- } else {
- strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
- cached_off = 0;
- cached_data = 1;
+static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
+ for (const auto& entry : fstab_default) {
+ if (!entry.fs_mgr_flags.vold_managed &&
+ (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
+ entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
+ if (key_loc != nullptr) {
+ *key_loc = entry.key_loc;
+ }
+ if (real_blk_device != nullptr) {
+ *real_blk_device = entry.blk_device;
+ }
+ return;
+ }
}
- }
+}
- if (cached_data) {
- if (metadata_fname) {
- *metadata_fname = cached_metadata_fname;
- }
- if (off) {
- *off = cached_off;
- }
- rc = 0;
- }
+static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
+ static int cached_data = 0;
+ static uint64_t cached_off = 0;
+ static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
+ char key_loc[PROPERTY_VALUE_MAX];
+ char real_blkdev[PROPERTY_VALUE_MAX];
+ int rc = -1;
- return rc;
+ if (!cached_data) {
+ std::string key_loc;
+ std::string real_blkdev;
+ get_crypt_info(&key_loc, &real_blkdev);
+
+ if (key_loc == KEY_IN_FOOTER) {
+ if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
+ /* If it's an encrypted Android partition, the last 16 Kbytes contain the
+ * encryption info footer and key, and plenty of bytes to spare for future
+ * growth.
+ */
+ strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
+ cached_off -= CRYPT_FOOTER_OFFSET;
+ cached_data = 1;
+ } else {
+ SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
+ }
+ } else {
+ strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
+ cached_off = 0;
+ cached_data = 1;
+ }
+ }
+
+ if (cached_data) {
+ if (metadata_fname) {
+ *metadata_fname = cached_metadata_fname;
+ }
+ if (off) {
+ *off = cached_off;
+ }
+ rc = 0;
+ }
+
+ return rc;
}
/* Set sha256 checksum in structure */
-static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
-{
+static void set_ftr_sha(struct crypt_mnt_ftr* crypt_ftr) {
SHA256_CTX c;
SHA256_Init(&c);
memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
@@ -502,82 +512,76 @@
/* key or salt can be NULL, in which case just skip writing that value. Useful to
* update the failed mount count but not change the key.
*/
-static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
-{
- int fd;
- unsigned int cnt;
- /* starting_off is set to the SEEK_SET offset
- * where the crypto structure starts
- */
- off64_t starting_off;
- int rc = -1;
- char *fname = NULL;
- struct stat statbuf;
+static int put_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
+ int fd;
+ unsigned int cnt;
+ /* starting_off is set to the SEEK_SET offset
+ * where the crypto structure starts
+ */
+ off64_t starting_off;
+ int rc = -1;
+ char* fname = NULL;
+ struct stat statbuf;
- set_ftr_sha(crypt_ftr);
+ set_ftr_sha(crypt_ftr);
- if (get_crypt_ftr_info(&fname, &starting_off)) {
- SLOGE("Unable to get crypt_ftr_info\n");
- return -1;
- }
- if (fname[0] != '/') {
- SLOGE("Unexpected value for crypto key location\n");
- return -1;
- }
- if ( (fd = open(fname, O_RDWR | O_CREAT|O_CLOEXEC, 0600)) < 0) {
- SLOGE("Cannot open footer file %s for put\n", fname);
- return -1;
- }
-
- /* Seek to the start of the crypt footer */
- if (lseek64(fd, starting_off, SEEK_SET) == -1) {
- SLOGE("Cannot seek to real block device footer\n");
- goto errout;
- }
-
- if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
- SLOGE("Cannot write real block device footer\n");
- goto errout;
- }
-
- fstat(fd, &statbuf);
- /* If the keys are kept on a raw block device, do not try to truncate it. */
- if (S_ISREG(statbuf.st_mode)) {
- if (ftruncate(fd, 0x4000)) {
- SLOGE("Cannot set footer file size\n");
- goto errout;
+ if (get_crypt_ftr_info(&fname, &starting_off)) {
+ SLOGE("Unable to get crypt_ftr_info\n");
+ return -1;
}
- }
+ if (fname[0] != '/') {
+ SLOGE("Unexpected value for crypto key location\n");
+ return -1;
+ }
+ if ((fd = open(fname, O_RDWR | O_CREAT | O_CLOEXEC, 0600)) < 0) {
+ SLOGE("Cannot open footer file %s for put\n", fname);
+ return -1;
+ }
- /* Success! */
- rc = 0;
+ /* Seek to the start of the crypt footer */
+ if (lseek64(fd, starting_off, SEEK_SET) == -1) {
+ SLOGE("Cannot seek to real block device footer\n");
+ goto errout;
+ }
+
+ if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
+ SLOGE("Cannot write real block device footer\n");
+ goto errout;
+ }
+
+ fstat(fd, &statbuf);
+ /* If the keys are kept on a raw block device, do not try to truncate it. */
+ if (S_ISREG(statbuf.st_mode)) {
+ if (ftruncate(fd, 0x4000)) {
+ SLOGE("Cannot set footer file size\n");
+ goto errout;
+ }
+ }
+
+ /* Success! */
+ rc = 0;
errout:
- close(fd);
- return rc;
-
+ close(fd);
+ return rc;
}
-static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
-{
+static bool check_ftr_sha(const struct crypt_mnt_ftr* crypt_ftr) {
struct crypt_mnt_ftr copy;
memcpy(©, crypt_ftr, sizeof(copy));
set_ftr_sha(©);
return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
}
-static inline int unix_read(int fd, void* buff, int len)
-{
+static inline int unix_read(int fd, void* buff, int len) {
return TEMP_FAILURE_RETRY(read(fd, buff, len));
}
-static inline int unix_write(int fd, const void* buff, int len)
-{
+static inline int unix_write(int fd, const void* buff, int len) {
return TEMP_FAILURE_RETRY(write(fd, buff, len));
}
-static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
-{
+static void init_empty_persist_data(struct crypt_persist_data* pdata, int len) {
memset(pdata, 0, len);
pdata->persist_magic = PERSIST_DATA_MAGIC;
pdata->persist_valid_entries = 0;
@@ -588,18 +592,17 @@
* data, crypt_ftr is a pointer to the struct to be updated, and offset is the
* absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
*/
-static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
-{
+static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr* crypt_ftr, off64_t offset) {
int orig_major = crypt_ftr->major_version;
int orig_minor = crypt_ftr->minor_version;
if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
- struct crypt_persist_data *pdata;
+ struct crypt_persist_data* pdata;
off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
SLOGW("upgrading crypto footer to 1.1");
- pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
+ pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
if (pdata == NULL) {
SLOGE("Cannot allocate persisent data\n");
return;
@@ -652,91 +655,89 @@
}
}
+static int get_crypt_ftr_and_key(struct crypt_mnt_ftr* crypt_ftr) {
+ int fd;
+ unsigned int cnt;
+ off64_t starting_off;
+ int rc = -1;
+ char* fname = NULL;
+ struct stat statbuf;
-static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
-{
- int fd;
- unsigned int cnt;
- off64_t starting_off;
- int rc = -1;
- char *fname = NULL;
- struct stat statbuf;
+ if (get_crypt_ftr_info(&fname, &starting_off)) {
+ SLOGE("Unable to get crypt_ftr_info\n");
+ return -1;
+ }
+ if (fname[0] != '/') {
+ SLOGE("Unexpected value for crypto key location\n");
+ return -1;
+ }
+ if ((fd = open(fname, O_RDWR | O_CLOEXEC)) < 0) {
+ SLOGE("Cannot open footer file %s for get\n", fname);
+ return -1;
+ }
- if (get_crypt_ftr_info(&fname, &starting_off)) {
- SLOGE("Unable to get crypt_ftr_info\n");
- return -1;
- }
- if (fname[0] != '/') {
- SLOGE("Unexpected value for crypto key location\n");
- return -1;
- }
- if ( (fd = open(fname, O_RDWR|O_CLOEXEC)) < 0) {
- SLOGE("Cannot open footer file %s for get\n", fname);
- return -1;
- }
+ /* Make sure it's 16 Kbytes in length */
+ fstat(fd, &statbuf);
+ if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
+ SLOGE("footer file %s is not the expected size!\n", fname);
+ goto errout;
+ }
- /* Make sure it's 16 Kbytes in length */
- fstat(fd, &statbuf);
- if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
- SLOGE("footer file %s is not the expected size!\n", fname);
- goto errout;
- }
+ /* Seek to the start of the crypt footer */
+ if (lseek64(fd, starting_off, SEEK_SET) == -1) {
+ SLOGE("Cannot seek to real block device footer\n");
+ goto errout;
+ }
- /* Seek to the start of the crypt footer */
- if (lseek64(fd, starting_off, SEEK_SET) == -1) {
- SLOGE("Cannot seek to real block device footer\n");
- goto errout;
- }
+ if ((cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
+ SLOGE("Cannot read real block device footer\n");
+ goto errout;
+ }
- if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
- SLOGE("Cannot read real block device footer\n");
- goto errout;
- }
+ if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
+ SLOGE("Bad magic for real block device %s\n", fname);
+ goto errout;
+ }
- if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
- SLOGE("Bad magic for real block device %s\n", fname);
- goto errout;
- }
+ if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
+ SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
+ crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
+ goto errout;
+ }
- if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
- SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
- crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
- goto errout;
- }
+ // We risk buffer overflows with oversized keys, so we just reject them.
+ // 0-sized keys are problematic (essentially by-passing encryption), and
+ // AES-CBC key wrapping only works for multiples of 16 bytes.
+ if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
+ (crypt_ftr->keysize > MAX_KEY_LEN)) {
+ SLOGE(
+ "Invalid keysize (%u) for block device %s; Must be non-zero, "
+ "divisible by 16, and <= %d\n",
+ crypt_ftr->keysize, fname, MAX_KEY_LEN);
+ goto errout;
+ }
- // We risk buffer overflows with oversized keys, so we just reject them.
- // 0-sized keys are problematic (essentially by-passing encryption), and
- // AES-CBC key wrapping only works for multiples of 16 bytes.
- if ((crypt_ftr->keysize == 0) || ((crypt_ftr->keysize % 16) != 0) ||
- (crypt_ftr->keysize > MAX_KEY_LEN)) {
- SLOGE("Invalid keysize (%u) for block device %s; Must be non-zero, "
- "divisible by 16, and <= %d\n", crypt_ftr->keysize, fname,
- MAX_KEY_LEN);
- goto errout;
- }
+ if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
+ SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
+ crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
+ }
- if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
- SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
- crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
- }
+ /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
+ * copy on disk before returning.
+ */
+ if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
+ upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
+ }
- /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
- * copy on disk before returning.
- */
- if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
- upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
- }
-
- /* Success! */
- rc = 0;
+ /* Success! */
+ rc = 0;
errout:
- close(fd);
- return rc;
+ close(fd);
+ return rc;
}
-static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
-{
+static int validate_persistent_data_storage(struct crypt_mnt_ftr* crypt_ftr) {
if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
crypt_ftr->persist_data_offset[1]) {
SLOGE("Crypt_ftr persist data regions overlap");
@@ -749,7 +750,7 @@
}
if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
- (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
+ (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
CRYPT_FOOTER_OFFSET) {
SLOGE("Persistent data extends past crypto footer");
return -1;
@@ -758,12 +759,11 @@
return 0;
}
-static int load_persistent_data(void)
-{
+static int load_persistent_data(void) {
struct crypt_mnt_ftr crypt_ftr;
- struct crypt_persist_data *pdata = NULL;
+ struct crypt_persist_data* pdata = NULL;
char encrypted_state[PROPERTY_VALUE_MAX];
- char *fname;
+ char* fname;
int found = 0;
int fd;
int ret;
@@ -774,10 +774,9 @@
return 0;
}
-
/* If not encrypted, just allocate an empty table and initialize it */
property_get("ro.crypto.state", encrypted_state, "");
- if (strcmp(encrypted_state, "encrypted") ) {
+ if (strcmp(encrypted_state, "encrypted")) {
pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
if (pdata) {
init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
@@ -787,12 +786,12 @@
return -1;
}
- if(get_crypt_ftr_and_key(&crypt_ftr)) {
+ if (get_crypt_ftr_and_key(&crypt_ftr)) {
return -1;
}
- if ((crypt_ftr.major_version < 1)
- || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
+ if ((crypt_ftr.major_version < 1) ||
+ (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
SLOGE("Crypt_ftr version doesn't support persistent data");
return -1;
}
@@ -806,7 +805,7 @@
return -1;
}
- fd = open(fname, O_RDONLY|O_CLOEXEC);
+ fd = open(fname, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
SLOGE("Cannot open %s metadata file", fname);
return -1;
@@ -823,7 +822,7 @@
SLOGE("Cannot seek to read persistent data on %s", fname);
goto err2;
}
- if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
+ if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
SLOGE("Error reading persistent data on iteration %d", i);
goto err2;
}
@@ -851,11 +850,10 @@
return -1;
}
-static int save_persistent_data(void)
-{
+static int save_persistent_data(void) {
struct crypt_mnt_ftr crypt_ftr;
- struct crypt_persist_data *pdata;
- char *fname;
+ struct crypt_persist_data* pdata;
+ char* fname;
off64_t write_offset;
off64_t erase_offset;
int fd;
@@ -866,12 +864,12 @@
return -1;
}
- if(get_crypt_ftr_and_key(&crypt_ftr)) {
+ if (get_crypt_ftr_and_key(&crypt_ftr)) {
return -1;
}
- if ((crypt_ftr.major_version < 1)
- || (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
+ if ((crypt_ftr.major_version < 1) ||
+ (crypt_ftr.major_version == 1 && crypt_ftr.minor_version < 1)) {
SLOGE("Crypt_ftr version doesn't support persistent data");
return -1;
}
@@ -885,7 +883,7 @@
return -1;
}
- fd = open(fname, O_RDWR|O_CLOEXEC);
+ fd = open(fname, O_RDWR | O_CLOEXEC);
if (fd < 0) {
SLOGE("Cannot open %s metadata file", fname);
return -1;
@@ -903,20 +901,20 @@
}
if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
- SLOGE("Error reading persistent data before save");
- goto err2;
+ SLOGE("Error reading persistent data before save");
+ goto err2;
}
if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
/* The first copy is the curent valid copy, so write to
* the second copy and erase this one */
- write_offset = crypt_ftr.persist_data_offset[1];
- erase_offset = crypt_ftr.persist_data_offset[0];
+ write_offset = crypt_ftr.persist_data_offset[1];
+ erase_offset = crypt_ftr.persist_data_offset[0];
} else {
/* The second copy must be the valid copy, so write to
* the first copy, and erase the second */
- write_offset = crypt_ftr.persist_data_offset[0];
- erase_offset = crypt_ftr.persist_data_offset[1];
+ write_offset = crypt_ftr.persist_data_offset[0];
+ erase_offset = crypt_ftr.persist_data_offset[1];
}
/* Write the new copy first, if successful, then erase the old copy */
@@ -925,15 +923,14 @@
goto err2;
}
if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
- (int) crypt_ftr.persist_data_size) {
+ (int)crypt_ftr.persist_data_size) {
if (lseek64(fd, erase_offset, SEEK_SET) < 0) {
SLOGE("Cannot seek to erase previous persistent data");
goto err2;
}
fsync(fd);
memset(pdata, 0, crypt_ftr.persist_data_size);
- if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
- (int) crypt_ftr.persist_data_size) {
+ if (unix_write(fd, pdata, crypt_ftr.persist_data_size) != (int)crypt_ftr.persist_data_size) {
SLOGE("Cannot write to erase previous persistent data");
goto err2;
}
@@ -958,85 +955,85 @@
/* Convert a binary key of specified length into an ascii hex string equivalent,
* without the leading 0x and with null termination
*/
-static void convert_key_to_hex_ascii(const unsigned char *master_key,
- unsigned int keysize, char *master_key_ascii) {
+static void convert_key_to_hex_ascii(const unsigned char* master_key, unsigned int keysize,
+ char* master_key_ascii) {
unsigned int i, a;
unsigned char nibble;
- for (i=0, a=0; i<keysize; i++, a+=2) {
+ for (i = 0, a = 0; i < keysize; i++, a += 2) {
/* For each byte, write out two ascii hex digits */
nibble = (master_key[i] >> 4) & 0xf;
master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
nibble = master_key[i] & 0xf;
- master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
+ master_key_ascii[a + 1] = nibble + (nibble > 9 ? 0x37 : 0x30);
}
/* Add the null termination */
master_key_ascii[a] = '\0';
-
}
-static int load_crypto_mapping_table(struct crypt_mnt_ftr *crypt_ftr,
- const unsigned char *master_key, const char *real_blk_name,
- const char *name, int fd, const char *extra_params) {
- alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
- struct dm_ioctl *io;
- struct dm_target_spec *tgt;
- char *crypt_params;
- // We need two ASCII characters to represent each byte, and need space for
- // the '\0' terminator.
- char master_key_ascii[MAX_KEY_LEN * 2 + 1];
- size_t buff_offset;
- int i;
+static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
+ const unsigned char* master_key, const char* real_blk_name,
+ const char* name, int fd, const char* extra_params) {
+ alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
+ struct dm_ioctl* io;
+ struct dm_target_spec* tgt;
+ char* crypt_params;
+ // We need two ASCII characters to represent each byte, and need space for
+ // the '\0' terminator.
+ char master_key_ascii[MAX_KEY_LEN * 2 + 1];
+ size_t buff_offset;
+ int i;
- io = (struct dm_ioctl *) buffer;
+ io = (struct dm_ioctl*)buffer;
- /* Load the mapping table for this device */
- tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
+ /* Load the mapping table for this device */
+ tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
- io->target_count = 1;
- tgt->status = 0;
- tgt->sector_start = 0;
- tgt->length = crypt_ftr->fs_size;
- strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
+ ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
+ io->target_count = 1;
+ tgt->status = 0;
+ tgt->sector_start = 0;
+ tgt->length = crypt_ftr->fs_size;
+ strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
- crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
- convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
+ crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
+ convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
- buff_offset = crypt_params - buffer;
- SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
- snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
- crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name,
- extra_params);
- crypt_params += strlen(crypt_params) + 1;
- crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
- tgt->next = crypt_params - buffer;
+ buff_offset = crypt_params - buffer;
+ SLOGI(
+ "Creating crypto dev \"%s\"; cipher=%s, keysize=%u, real_dev=%s, len=%llu, params=\"%s\"\n",
+ name, crypt_ftr->crypto_type_name, crypt_ftr->keysize, real_blk_name, tgt->length * 512,
+ extra_params);
+ snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
+ crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
+ crypt_params += strlen(crypt_params) + 1;
+ crypt_params =
+ (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
+ tgt->next = crypt_params - buffer;
- for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
- if (! ioctl(fd, DM_TABLE_LOAD, io)) {
- break;
+ for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
+ if (!ioctl(fd, DM_TABLE_LOAD, io)) {
+ break;
+ }
+ usleep(500000);
}
- usleep(500000);
- }
- if (i == TABLE_LOAD_RETRIES) {
- /* We failed to load the table, return an error */
- return -1;
- } else {
- return i + 1;
- }
+ if (i == TABLE_LOAD_RETRIES) {
+ /* We failed to load the table, return an error */
+ return -1;
+ } else {
+ return i + 1;
+ }
}
-
-static int get_dm_crypt_version(int fd, const char *name, int *version)
-{
+static int get_dm_crypt_version(int fd, const char* name, int* version) {
char buffer[DM_CRYPT_BUF_SIZE];
- struct dm_ioctl *io;
- struct dm_target_versions *v;
+ struct dm_ioctl* io;
+ struct dm_target_versions* v;
- io = (struct dm_ioctl *) buffer;
+ io = (struct dm_ioctl*)buffer;
ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
@@ -1047,16 +1044,16 @@
/* Iterate over the returned versions, looking for name of "crypt".
* When found, get and return the version.
*/
- v = (struct dm_target_versions *) &buffer[sizeof(struct dm_ioctl)];
+ v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
while (v->next) {
- if (! strcmp(v->name, "crypt")) {
+ if (!strcmp(v->name, "crypt")) {
/* We found the crypt driver, return the version, and get out */
version[0] = v->version[0];
version[1] = v->version[1];
version[2] = v->version[2];
return 0;
}
- v = (struct dm_target_versions *)(((char *)v) + v->next);
+ v = (struct dm_target_versions*)(((char*)v) + v->next);
}
return -1;
@@ -1072,6 +1069,39 @@
return extra_params;
}
+/*
+ * If the ro.crypto.fde_sector_size system property is set, append the
+ * parameters to make dm-crypt use the specified crypto sector size and round
+ * the crypto device size down to a crypto sector boundary.
+ */
+static int add_sector_size_param(std::vector<std::string>* extra_params_vec,
+ struct crypt_mnt_ftr* ftr) {
+ constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
+ char value[PROPERTY_VALUE_MAX];
+
+ if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
+ unsigned int sector_size;
+
+ if (!ParseUint(value, §or_size) || sector_size < 512 || sector_size > 4096 ||
+ (sector_size & (sector_size - 1)) != 0) {
+ SLOGE("Invalid value for %s: %s. Must be >= 512, <= 4096, and a power of 2\n",
+ DM_CRYPT_SECTOR_SIZE, value);
+ return -1;
+ }
+
+ std::string param = StringPrintf("sector_size:%u", sector_size);
+ extra_params_vec->push_back(std::move(param));
+
+ // With this option, IVs will match the sector numbering, instead
+ // of being hard-coded to being based on 512-byte sectors.
+ extra_params_vec->emplace_back("iv_large_sectors");
+
+ // Round the crypto device size down to a crypto sector boundary.
+ ftr->fs_size &= ~((sector_size / 512) - 1);
+ }
+ return 0;
+}
+
static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
const char* real_blk_name, char* crypto_blk_name, const char* name,
uint32_t flags) {
@@ -1117,6 +1147,10 @@
if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
extra_params_vec.emplace_back("allow_encrypt_override");
}
+ if (add_sector_size_param(&extra_params_vec, crypt_ftr)) {
+ SLOGE("Error processing dm-crypt sector size param\n");
+ goto errout;
+ }
load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
extra_params_as_string(extra_params_vec).c_str());
if (load_count < 0) {
@@ -1134,91 +1168,90 @@
goto errout;
}
+ /* Ensure the dm device has been created before returning. */
+ if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
+ // WaitForFile generates a suitable log message
+ goto errout;
+ }
+
/* We made it here with no errors. Woot! */
retval = 0;
errout:
- close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
+ close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
- return retval;
+ return retval;
}
-static int delete_crypto_blk_dev(const char *name)
-{
- int fd;
- char buffer[DM_CRYPT_BUF_SIZE];
- struct dm_ioctl *io;
- int retval = -1;
+static int delete_crypto_blk_dev(const char* name) {
+ int fd;
+ char buffer[DM_CRYPT_BUF_SIZE];
+ struct dm_ioctl* io;
+ int retval = -1;
+ int err;
- if ((fd = open("/dev/device-mapper", O_RDWR|O_CLOEXEC)) < 0 ) {
- SLOGE("Cannot open device-mapper\n");
- goto errout;
- }
+ if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
+ SLOGE("Cannot open device-mapper\n");
+ goto errout;
+ }
- io = (struct dm_ioctl *) buffer;
+ io = (struct dm_ioctl*)buffer;
- ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
- if (ioctl(fd, DM_DEV_REMOVE, io)) {
- SLOGE("Cannot remove dm-crypt device\n");
- goto errout;
- }
+ ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
+ err = ioctl(fd, DM_DEV_REMOVE, io);
+ if (err) {
+ SLOGE("Cannot remove dm-crypt device %s: %s\n", name, strerror(errno));
+ goto errout;
+ }
- /* We made it here with no errors. Woot! */
- retval = 0;
+ /* We made it here with no errors. Woot! */
+ retval = 0;
errout:
- close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
+ close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
- return retval;
-
+ return retval;
}
-static int pbkdf2(const char *passwd, const unsigned char *salt,
- unsigned char *ikey, void *params UNUSED)
-{
+static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
+ void* params UNUSED) {
SLOGI("Using pbkdf2 for cryptfs KDF");
/* Turn the password into a key and IV that can decrypt the master key */
- return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
- HASH_COUNT, INTERMEDIATE_BUF_SIZE,
- ikey) != 1;
+ return PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN, HASH_COUNT,
+ INTERMEDIATE_BUF_SIZE, ikey) != 1;
}
-static int scrypt(const char *passwd, const unsigned char *salt,
- unsigned char *ikey, void *params)
-{
+static int scrypt(const char* passwd, const unsigned char* salt, unsigned char* ikey, void* params) {
SLOGI("Using scrypt for cryptfs KDF");
- struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
+ struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
int N = 1 << ftr->N_factor;
int r = 1 << ftr->r_factor;
int p = 1 << ftr->p_factor;
/* Turn the password into a key and IV that can decrypt the master key */
- crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
- salt, SALT_LEN, N, r, p, ikey,
+ crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
INTERMEDIATE_BUF_SIZE);
- return 0;
+ return 0;
}
-static int scrypt_keymaster(const char *passwd, const unsigned char *salt,
- unsigned char *ikey, void *params)
-{
+static int scrypt_keymaster(const char* passwd, const unsigned char* salt, unsigned char* ikey,
+ void* params) {
SLOGI("Using scrypt with keymaster for cryptfs KDF");
int rc;
size_t signature_size;
unsigned char* signature;
- struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
+ struct crypt_mnt_ftr* ftr = (struct crypt_mnt_ftr*)params;
int N = 1 << ftr->N_factor;
int r = 1 << ftr->r_factor;
int p = 1 << ftr->p_factor;
- rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd),
- salt, SALT_LEN, N, r, p, ikey,
+ rc = crypto_scrypt((const uint8_t*)passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
INTERMEDIATE_BUF_SIZE);
if (rc) {
@@ -1226,14 +1259,13 @@
return -1;
}
- if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE,
- &signature, &signature_size)) {
+ if (keymaster_sign_object(ftr, ikey, INTERMEDIATE_BUF_SIZE, &signature, &signature_size)) {
SLOGE("Signing failed");
return -1;
}
- rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN,
- N, r, p, ikey, INTERMEDIATE_BUF_SIZE);
+ rc = crypto_scrypt(signature, signature_size, salt, SALT_LEN, N, r, p, ikey,
+ INTERMEDIATE_BUF_SIZE);
free(signature);
if (rc) {
@@ -1244,12 +1276,10 @@
return 0;
}
-static int encrypt_master_key(const char *passwd, const unsigned char *salt,
- const unsigned char *decrypted_master_key,
- unsigned char *encrypted_master_key,
- struct crypt_mnt_ftr *crypt_ftr)
-{
- unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
+static int encrypt_master_key(const char* passwd, const unsigned char* salt,
+ const unsigned char* decrypted_master_key,
+ unsigned char* encrypted_master_key, struct crypt_mnt_ftr* crypt_ftr) {
+ unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
EVP_CIPHER_CTX e_ctx;
int encrypted_len, final_len;
int rc = 0;
@@ -1258,46 +1288,46 @@
get_device_scrypt_params(crypt_ftr);
switch (crypt_ftr->kdf_type) {
- case KDF_SCRYPT_KEYMASTER:
- if (keymaster_create_key(crypt_ftr)) {
- SLOGE("keymaster_create_key failed");
- return -1;
- }
+ case KDF_SCRYPT_KEYMASTER:
+ if (keymaster_create_key(crypt_ftr)) {
+ SLOGE("keymaster_create_key failed");
+ return -1;
+ }
- if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
- SLOGE("scrypt failed");
- return -1;
- }
- break;
+ if (scrypt_keymaster(passwd, salt, ikey, crypt_ftr)) {
+ SLOGE("scrypt failed");
+ return -1;
+ }
+ break;
- case KDF_SCRYPT:
- if (scrypt(passwd, salt, ikey, crypt_ftr)) {
- SLOGE("scrypt failed");
- return -1;
- }
- break;
+ case KDF_SCRYPT:
+ if (scrypt(passwd, salt, ikey, crypt_ftr)) {
+ SLOGE("scrypt failed");
+ return -1;
+ }
+ break;
- default:
- SLOGE("Invalid kdf_type");
- return -1;
+ default:
+ SLOGE("Invalid kdf_type");
+ return -1;
}
/* Initialize the decryption engine */
EVP_CIPHER_CTX_init(&e_ctx);
- if (! EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
- ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
+ if (!EVP_EncryptInit_ex(&e_ctx, EVP_aes_128_cbc(), NULL, ikey,
+ ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
SLOGE("EVP_EncryptInit failed\n");
return -1;
}
EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
/* Encrypt the master key */
- if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
- decrypted_master_key, crypt_ftr->keysize)) {
+ if (!EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len, decrypted_master_key,
+ crypt_ftr->keysize)) {
SLOGE("EVP_EncryptUpdate failed\n");
return -1;
}
- if (! EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
+ if (!EVP_EncryptFinal_ex(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
SLOGE("EVP_EncryptFinal failed\n");
return -1;
}
@@ -1316,13 +1346,12 @@
int r = 1 << crypt_ftr->r_factor;
int p = 1 << crypt_ftr->p_factor;
- rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES,
- crypt_ftr->salt, sizeof(crypt_ftr->salt), N, r, p,
- crypt_ftr->scrypted_intermediate_key,
+ rc = crypto_scrypt(ikey, INTERMEDIATE_KEY_LEN_BYTES, crypt_ftr->salt, sizeof(crypt_ftr->salt),
+ N, r, p, crypt_ftr->scrypted_intermediate_key,
sizeof(crypt_ftr->scrypted_intermediate_key));
if (rc) {
- SLOGE("encrypt_master_key: crypto_scrypt failed");
+ SLOGE("encrypt_master_key: crypto_scrypt failed");
}
EVP_CIPHER_CTX_cleanup(&e_ctx);
@@ -1330,60 +1359,57 @@
return 0;
}
-static int decrypt_master_key_aux(const char *passwd, unsigned char *salt,
- const unsigned char *encrypted_master_key,
- size_t keysize,
- unsigned char *decrypted_master_key,
- kdf_func kdf, void *kdf_params,
- unsigned char** intermediate_key,
- size_t* intermediate_key_size)
-{
- unsigned char ikey[INTERMEDIATE_BUF_SIZE] = { 0 };
- EVP_CIPHER_CTX d_ctx;
- int decrypted_len, final_len;
+static int decrypt_master_key_aux(const char* passwd, unsigned char* salt,
+ const unsigned char* encrypted_master_key, size_t keysize,
+ unsigned char* decrypted_master_key, kdf_func kdf,
+ void* kdf_params, unsigned char** intermediate_key,
+ size_t* intermediate_key_size) {
+ unsigned char ikey[INTERMEDIATE_BUF_SIZE] = {0};
+ EVP_CIPHER_CTX d_ctx;
+ int decrypted_len, final_len;
- /* Turn the password into an intermediate key and IV that can decrypt the
- master key */
- if (kdf(passwd, salt, ikey, kdf_params)) {
- SLOGE("kdf failed");
- return -1;
- }
-
- /* Initialize the decryption engine */
- EVP_CIPHER_CTX_init(&d_ctx);
- if (! EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey, ikey+INTERMEDIATE_KEY_LEN_BYTES)) {
- return -1;
- }
- EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
- /* Decrypt the master key */
- if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
- encrypted_master_key, keysize)) {
- return -1;
- }
- if (! EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
- return -1;
- }
-
- if (decrypted_len + final_len != static_cast<int>(keysize)) {
- return -1;
- }
-
- /* Copy intermediate key if needed by params */
- if (intermediate_key && intermediate_key_size) {
- *intermediate_key = (unsigned char*) malloc(INTERMEDIATE_KEY_LEN_BYTES);
- if (*intermediate_key) {
- memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
- *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
+ /* Turn the password into an intermediate key and IV that can decrypt the
+ master key */
+ if (kdf(passwd, salt, ikey, kdf_params)) {
+ SLOGE("kdf failed");
+ return -1;
}
- }
- EVP_CIPHER_CTX_cleanup(&d_ctx);
+ /* Initialize the decryption engine */
+ EVP_CIPHER_CTX_init(&d_ctx);
+ if (!EVP_DecryptInit_ex(&d_ctx, EVP_aes_128_cbc(), NULL, ikey,
+ ikey + INTERMEDIATE_KEY_LEN_BYTES)) {
+ return -1;
+ }
+ EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
+ /* Decrypt the master key */
+ if (!EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len, encrypted_master_key,
+ keysize)) {
+ return -1;
+ }
+ if (!EVP_DecryptFinal_ex(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
+ return -1;
+ }
- return 0;
+ if (decrypted_len + final_len != static_cast<int>(keysize)) {
+ return -1;
+ }
+
+ /* Copy intermediate key if needed by params */
+ if (intermediate_key && intermediate_key_size) {
+ *intermediate_key = (unsigned char*)malloc(INTERMEDIATE_KEY_LEN_BYTES);
+ if (*intermediate_key) {
+ memcpy(*intermediate_key, ikey, INTERMEDIATE_KEY_LEN_BYTES);
+ *intermediate_key_size = INTERMEDIATE_KEY_LEN_BYTES;
+ }
+ }
+
+ EVP_CIPHER_CTX_cleanup(&d_ctx);
+
+ return 0;
}
-static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
-{
+static void get_kdf_func(struct crypt_mnt_ftr* ftr, kdf_func* kdf, void** kdf_params) {
if (ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
*kdf = scrypt_keymaster;
*kdf_params = ftr;
@@ -1396,20 +1422,17 @@
}
}
-static int decrypt_master_key(const char *passwd, unsigned char *decrypted_master_key,
- struct crypt_mnt_ftr *crypt_ftr,
- unsigned char** intermediate_key,
- size_t* intermediate_key_size)
-{
+static int decrypt_master_key(const char* passwd, unsigned char* decrypted_master_key,
+ struct crypt_mnt_ftr* crypt_ftr, unsigned char** intermediate_key,
+ size_t* intermediate_key_size) {
kdf_func kdf;
- void *kdf_params;
+ void* kdf_params;
int ret;
get_kdf_func(crypt_ftr, &kdf, &kdf_params);
- ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key,
- crypt_ftr->keysize,
- decrypted_master_key, kdf, kdf_params,
- intermediate_key, intermediate_key_size);
+ ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, crypt_ftr->keysize,
+ decrypted_master_key, kdf, kdf_params, intermediate_key,
+ intermediate_key_size);
if (ret != 0) {
SLOGW("failure decrypting master key");
}
@@ -1417,28 +1440,28 @@
return ret;
}
-static int create_encrypted_random_key(const char *passwd, unsigned char *master_key, unsigned char *salt,
- struct crypt_mnt_ftr *crypt_ftr) {
- int fd;
+static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
+ unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
unsigned char key_buf[MAX_KEY_LEN];
- /* Get some random bits for a key */
- fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
- read(fd, key_buf, sizeof(key_buf));
- read(fd, salt, SALT_LEN);
- close(fd);
+ /* Get some random bits for a key and salt */
+ if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
+ return -1;
+ }
+ if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
+ return -1;
+ }
/* Now encrypt it with the password */
return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
}
-int wait_and_unmount(const char *mountpoint, bool kill)
-{
+int wait_and_unmount(const char* mountpoint, bool kill) {
int i, err, rc;
#define WAIT_UNMOUNT_COUNT 20
/* Now umount the tmpfs filesystem */
- for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
+ for (i = 0; i < WAIT_UNMOUNT_COUNT; i++) {
if (umount(mountpoint) == 0) {
break;
}
@@ -1467,19 +1490,18 @@
}
if (i < WAIT_UNMOUNT_COUNT) {
- SLOGD("unmounting %s succeeded\n", mountpoint);
- rc = 0;
+ SLOGD("unmounting %s succeeded\n", mountpoint);
+ rc = 0;
} else {
- android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
- SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
- rc = -1;
+ android::vold::KillProcessesWithOpenFiles(mountpoint, 0);
+ SLOGE("unmounting %s failed: %s\n", mountpoint, strerror(err));
+ rc = -1;
}
return rc;
}
-static void prep_data_fs(void)
-{
+static void prep_data_fs(void) {
// NOTE: post_fs_data results in init calling back around to vold, so all
// callers to this method must be async
@@ -1489,17 +1511,14 @@
SLOGD("Just triggered post_fs_data");
/* Wait a max of 50 seconds, hopefully it takes much less */
- while (!android::base::WaitForProperty("vold.post_fs_data_done",
- "1",
- std::chrono::seconds(15))) {
+ while (!android::base::WaitForProperty("vold.post_fs_data_done", "1", std::chrono::seconds(15))) {
/* We timed out to prep /data in time. Continue wait. */
SLOGE("waited 15s for vold.post_fs_data_done, still waiting...");
}
SLOGD("post_fs_data done");
}
-static void cryptfs_set_corrupt()
-{
+static void cryptfs_set_corrupt() {
// Mark the footer as bad
struct crypt_mnt_ftr crypt_ftr;
if (get_crypt_ftr_and_key(&crypt_ftr)) {
@@ -1514,11 +1533,10 @@
}
}
-static void cryptfs_trigger_restart_min_framework()
-{
+static void cryptfs_trigger_restart_min_framework() {
if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
- SLOGE("Failed to mount tmpfs on data - panic");
- return;
+ SLOGE("Failed to mount tmpfs on data - panic");
+ return;
}
if (property_set("vold.decrypt", "trigger_post_fs_data")) {
@@ -1533,14 +1551,13 @@
}
/* returns < 0 on failure */
-static int cryptfs_restart_internal(int restart_main)
-{
+static int cryptfs_restart_internal(int restart_main) {
char crypto_blkdev[MAXPATHLEN];
int rc = -1;
static int restart_successful = 0;
/* Validate that it's OK to call this routine */
- if (! master_key_saved) {
+ if (!master_key_saved) {
SLOGE("Encrypted filesystem not validated, aborting");
return -1;
}
@@ -1589,7 +1606,7 @@
return -1;
}
- if (! (rc = wait_and_unmount(DATA_MNT_POINT, true)) ) {
+ if (!(rc = wait_and_unmount(DATA_MNT_POINT, true))) {
/* If ro.crypto.readonly is set to 1, mount the decrypted
* filesystem readonly. This is used when /data is mounted by
* recovery mode.
@@ -1597,8 +1614,10 @@
char ro_prop[PROPERTY_VALUE_MAX];
property_get("ro.crypto.readonly", ro_prop, "");
if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
- struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
- rec->flags |= MS_RDONLY;
+ auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
+ if (entry != nullptr) {
+ entry->flags |= MS_RDONLY;
+ }
}
/* If that succeeded, then mount the decrypted filesystem */
@@ -1609,19 +1628,18 @@
* fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
* partitions in the fsck domain.
*/
- if (setexeccon(secontextFsck())){
+ if (setexeccon(android::vold::sFsckContext)) {
SLOGE("Failed to setexeccon");
return -1;
}
- while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT,
- crypto_blkdev, 0))
- != 0) {
+ bool needs_cp = android::vold::cp_needsCheckpoint();
+ while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
+ needs_cp)) != 0) {
if (mount_rc == FS_MGR_DOMNT_BUSY) {
/* TODO: invoke something similar to
Process::killProcessWithOpenFiles(DATA_MNT_POINT,
retries > RETRY_MOUNT_ATTEMPT/2 ? 1 : 2 ) */
- SLOGI("Failed to mount %s because it is busy - waiting",
- crypto_blkdev);
+ SLOGI("Failed to mount %s because it is busy - waiting", crypto_blkdev);
if (--retries) {
sleep(RETRY_MOUNT_DELAY_SECONDS);
} else {
@@ -1664,10 +1682,9 @@
return rc;
}
-int cryptfs_restart(void)
-{
+int cryptfs_restart(void) {
SLOGI("cryptfs_restart");
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
SLOGE("cryptfs_restart not valid for file encryption:");
return -1;
}
@@ -1676,193 +1693,189 @@
return cryptfs_restart_internal(1);
}
-static int do_crypto_complete(const char *mount_point)
-{
- struct crypt_mnt_ftr crypt_ftr;
- char encrypted_state[PROPERTY_VALUE_MAX];
- char key_loc[PROPERTY_VALUE_MAX];
+static int do_crypto_complete(const char* mount_point) {
+ struct crypt_mnt_ftr crypt_ftr;
+ char encrypted_state[PROPERTY_VALUE_MAX];
- property_get("ro.crypto.state", encrypted_state, "");
- if (strcmp(encrypted_state, "encrypted") ) {
- SLOGE("not running with encryption, aborting");
- return CRYPTO_COMPLETE_NOT_ENCRYPTED;
- }
-
- // crypto_complete is full disk encrypted status
- if (e4crypt_is_native()) {
- return CRYPTO_COMPLETE_NOT_ENCRYPTED;
- }
-
- if (get_crypt_ftr_and_key(&crypt_ftr)) {
- fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
-
- /*
- * Only report this error if key_loc is a file and it exists.
- * If the device was never encrypted, and /data is not mountable for
- * some reason, returning 1 should prevent the UI from presenting the
- * a "enter password" screen, or worse, a "press button to wipe the
- * device" screen.
- */
- if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
- SLOGE("master key file does not exist, aborting");
- return CRYPTO_COMPLETE_NOT_ENCRYPTED;
- } else {
- SLOGE("Error getting crypt footer and key\n");
- return CRYPTO_COMPLETE_BAD_METADATA;
+ property_get("ro.crypto.state", encrypted_state, "");
+ if (strcmp(encrypted_state, "encrypted")) {
+ SLOGE("not running with encryption, aborting");
+ return CRYPTO_COMPLETE_NOT_ENCRYPTED;
}
- }
- // Test for possible error flags
- if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS){
- SLOGE("Encryption process is partway completed\n");
- return CRYPTO_COMPLETE_PARTIAL;
- }
+ // crypto_complete is full disk encrypted status
+ if (fscrypt_is_native()) {
+ return CRYPTO_COMPLETE_NOT_ENCRYPTED;
+ }
- if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE){
- SLOGE("Encryption process was interrupted but cannot continue\n");
- return CRYPTO_COMPLETE_INCONSISTENT;
- }
+ if (get_crypt_ftr_and_key(&crypt_ftr)) {
+ std::string key_loc;
+ get_crypt_info(&key_loc, nullptr);
- if (crypt_ftr.flags & CRYPT_DATA_CORRUPT){
- SLOGE("Encryption is successful but data is corrupt\n");
- return CRYPTO_COMPLETE_CORRUPT;
- }
+ /*
+ * Only report this error if key_loc is a file and it exists.
+ * If the device was never encrypted, and /data is not mountable for
+ * some reason, returning 1 should prevent the UI from presenting the
+ * a "enter password" screen, or worse, a "press button to wipe the
+ * device" screen.
+ */
+ if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
+ SLOGE("master key file does not exist, aborting");
+ return CRYPTO_COMPLETE_NOT_ENCRYPTED;
+ } else {
+ SLOGE("Error getting crypt footer and key\n");
+ return CRYPTO_COMPLETE_BAD_METADATA;
+ }
+ }
- /* We passed the test! We shall diminish, and return to the west */
- return CRYPTO_COMPLETE_ENCRYPTED;
+ // Test for possible error flags
+ if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
+ SLOGE("Encryption process is partway completed\n");
+ return CRYPTO_COMPLETE_PARTIAL;
+ }
+
+ if (crypt_ftr.flags & CRYPT_INCONSISTENT_STATE) {
+ SLOGE("Encryption process was interrupted but cannot continue\n");
+ return CRYPTO_COMPLETE_INCONSISTENT;
+ }
+
+ if (crypt_ftr.flags & CRYPT_DATA_CORRUPT) {
+ SLOGE("Encryption is successful but data is corrupt\n");
+ return CRYPTO_COMPLETE_CORRUPT;
+ }
+
+ /* We passed the test! We shall diminish, and return to the west */
+ return CRYPTO_COMPLETE_ENCRYPTED;
}
-static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr,
- const char *passwd, const char *mount_point, const char *label)
-{
- unsigned char decrypted_master_key[MAX_KEY_LEN];
- char crypto_blkdev[MAXPATHLEN];
- char real_blkdev[MAXPATHLEN];
- char tmp_mount_point[64];
- unsigned int orig_failed_decrypt_count;
- int rc;
- int use_keymaster = 0;
- int upgrade = 0;
- unsigned char* intermediate_key = 0;
- size_t intermediate_key_size = 0;
- int N = 1 << crypt_ftr->N_factor;
- int r = 1 << crypt_ftr->r_factor;
- int p = 1 << crypt_ftr->p_factor;
+static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
+ const char* mount_point, const char* label) {
+ unsigned char decrypted_master_key[MAX_KEY_LEN];
+ char crypto_blkdev[MAXPATHLEN];
+ std::string real_blkdev;
+ char tmp_mount_point[64];
+ unsigned int orig_failed_decrypt_count;
+ int rc;
+ int use_keymaster = 0;
+ int upgrade = 0;
+ unsigned char* intermediate_key = 0;
+ size_t intermediate_key_size = 0;
+ int N = 1 << crypt_ftr->N_factor;
+ int r = 1 << crypt_ftr->r_factor;
+ int p = 1 << crypt_ftr->p_factor;
- SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
- orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
+ SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr->fs_size);
+ orig_failed_decrypt_count = crypt_ftr->failed_decrypt_count;
- if (! (crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
- if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr,
- &intermediate_key, &intermediate_key_size)) {
- SLOGE("Failed to decrypt master key\n");
- rc = -1;
- goto errout;
+ if (!(crypt_ftr->flags & CRYPT_MNT_KEY_UNENCRYPTED)) {
+ if (decrypt_master_key(passwd, decrypted_master_key, crypt_ftr, &intermediate_key,
+ &intermediate_key_size)) {
+ SLOGE("Failed to decrypt master key\n");
+ rc = -1;
+ goto errout;
+ }
}
- }
- fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
+ get_crypt_info(nullptr, &real_blkdev);
- // Create crypto block device - all (non fatal) code paths
- // need it
- if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label, 0)) {
- SLOGE("Error creating decrypted block device\n");
- rc = -1;
- goto errout;
- }
+ // Create crypto block device - all (non fatal) code paths
+ // need it
+ if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
+ label, 0)) {
+ SLOGE("Error creating decrypted block device\n");
+ rc = -1;
+ goto errout;
+ }
- /* Work out if the problem is the password or the data */
- unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->
- scrypted_intermediate_key)];
+ /* Work out if the problem is the password or the data */
+ unsigned char scrypted_intermediate_key[sizeof(crypt_ftr->scrypted_intermediate_key)];
- rc = crypto_scrypt(intermediate_key, intermediate_key_size,
- crypt_ftr->salt, sizeof(crypt_ftr->salt),
- N, r, p, scrypted_intermediate_key,
- sizeof(scrypted_intermediate_key));
+ rc = crypto_scrypt(intermediate_key, intermediate_key_size, crypt_ftr->salt,
+ sizeof(crypt_ftr->salt), N, r, p, scrypted_intermediate_key,
+ sizeof(scrypted_intermediate_key));
- // Does the key match the crypto footer?
- if (rc == 0 && memcmp(scrypted_intermediate_key,
- crypt_ftr->scrypted_intermediate_key,
- sizeof(scrypted_intermediate_key)) == 0) {
- SLOGI("Password matches");
- rc = 0;
- } else {
- /* Try mounting the file system anyway, just in case the problem's with
- * the footer, not the key. */
- snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt",
- mount_point);
- mkdir(tmp_mount_point, 0755);
- if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
- SLOGE("Error temp mounting decrypted block device\n");
- delete_crypto_blk_dev(label);
-
- rc = ++crypt_ftr->failed_decrypt_count;
- put_crypt_ftr_and_key(crypt_ftr);
+ // Does the key match the crypto footer?
+ if (rc == 0 && memcmp(scrypted_intermediate_key, crypt_ftr->scrypted_intermediate_key,
+ sizeof(scrypted_intermediate_key)) == 0) {
+ SLOGI("Password matches");
+ rc = 0;
} else {
- /* Success! */
- SLOGI("Password did not match but decrypted drive mounted - continue");
- umount(tmp_mount_point);
- rc = 0;
- }
- }
+ /* Try mounting the file system anyway, just in case the problem's with
+ * the footer, not the key. */
+ snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
+ mkdir(tmp_mount_point, 0755);
+ if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
+ SLOGE("Error temp mounting decrypted block device\n");
+ delete_crypto_blk_dev(label);
- if (rc == 0) {
- crypt_ftr->failed_decrypt_count = 0;
- if (orig_failed_decrypt_count != 0) {
- put_crypt_ftr_and_key(crypt_ftr);
- }
-
- /* Save the name of the crypto block device
- * so we can mount it when restarting the framework. */
- property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
-
- /* Also save a the master key so we can reencrypted the key
- * the key when we want to change the password on it. */
- memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
- saved_mount_point = strdup(mount_point);
- master_key_saved = 1;
- SLOGD("%s(): Master key saved\n", __FUNCTION__);
- rc = 0;
-
- // Upgrade if we're not using the latest KDF.
- use_keymaster = keymaster_check_compatibility();
- if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
- // Don't allow downgrade
- } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
- crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
- upgrade = 1;
- } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
- crypt_ftr->kdf_type = KDF_SCRYPT;
- upgrade = 1;
- }
-
- if (upgrade) {
- rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
- crypt_ftr->master_key, crypt_ftr);
- if (!rc) {
- rc = put_crypt_ftr_and_key(crypt_ftr);
- }
- SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
-
- // Do not fail even if upgrade failed - machine is bootable
- // Note that if this code is ever hit, there is a *serious* problem
- // since KDFs should never fail. You *must* fix the kdf before
- // proceeding!
- if (rc) {
- SLOGW("Upgrade failed with error %d,"
- " but continuing with previous state",
- rc);
- rc = 0;
+ rc = ++crypt_ftr->failed_decrypt_count;
+ put_crypt_ftr_and_key(crypt_ftr);
+ } else {
+ /* Success! */
+ SLOGI("Password did not match but decrypted drive mounted - continue");
+ umount(tmp_mount_point);
+ rc = 0;
}
}
- }
- errout:
- if (intermediate_key) {
- memset(intermediate_key, 0, intermediate_key_size);
- free(intermediate_key);
- }
- return rc;
+ if (rc == 0) {
+ crypt_ftr->failed_decrypt_count = 0;
+ if (orig_failed_decrypt_count != 0) {
+ put_crypt_ftr_and_key(crypt_ftr);
+ }
+
+ /* Save the name of the crypto block device
+ * so we can mount it when restarting the framework. */
+ property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
+
+ /* Also save a the master key so we can reencrypted the key
+ * the key when we want to change the password on it. */
+ memcpy(saved_master_key, decrypted_master_key, crypt_ftr->keysize);
+ saved_mount_point = strdup(mount_point);
+ master_key_saved = 1;
+ SLOGD("%s(): Master key saved\n", __FUNCTION__);
+ rc = 0;
+
+ // Upgrade if we're not using the latest KDF.
+ use_keymaster = keymaster_check_compatibility();
+ if (crypt_ftr->kdf_type == KDF_SCRYPT_KEYMASTER) {
+ // Don't allow downgrade
+ } else if (use_keymaster == 1 && crypt_ftr->kdf_type != KDF_SCRYPT_KEYMASTER) {
+ crypt_ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
+ upgrade = 1;
+ } else if (use_keymaster == 0 && crypt_ftr->kdf_type != KDF_SCRYPT) {
+ crypt_ftr->kdf_type = KDF_SCRYPT;
+ upgrade = 1;
+ }
+
+ if (upgrade) {
+ rc = encrypt_master_key(passwd, crypt_ftr->salt, saved_master_key,
+ crypt_ftr->master_key, crypt_ftr);
+ if (!rc) {
+ rc = put_crypt_ftr_and_key(crypt_ftr);
+ }
+ SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
+
+ // Do not fail even if upgrade failed - machine is bootable
+ // Note that if this code is ever hit, there is a *serious* problem
+ // since KDFs should never fail. You *must* fix the kdf before
+ // proceeding!
+ if (rc) {
+ SLOGW(
+ "Upgrade failed with error %d,"
+ " but continuing with previous state",
+ rc);
+ rc = 0;
+ }
+ }
+ }
+
+errout:
+ if (intermediate_key) {
+ memset(intermediate_key, 0, intermediate_key_size);
+ free(intermediate_key);
+ }
+ return rc;
}
/*
@@ -1873,19 +1886,10 @@
*
* out_crypto_blkdev must be MAXPATHLEN.
*/
-int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
- const unsigned char* key, char* out_crypto_blkdev) {
- int fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
- if (fd == -1) {
- SLOGE("Failed to open %s: %s", real_blkdev, strerror(errno));
- return -1;
- }
-
- unsigned long nr_sec = 0;
- get_blkdev_size(fd, &nr_sec);
- close(fd);
-
- if (nr_sec == 0) {
+int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
+ char* out_crypto_blkdev) {
+ uint64_t nr_sec = 0;
+ if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
return -1;
}
@@ -1894,10 +1898,10 @@
memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
ext_crypt_ftr.fs_size = nr_sec;
ext_crypt_ftr.keysize = cryptfs_get_keysize();
- strlcpy((char*) ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
+ strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
MAX_CRYPTO_TYPE_NAME_LEN);
uint32_t flags = 0;
- if (e4crypt_is_native() &&
+ if (fscrypt_is_native() &&
android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
@@ -1909,21 +1913,20 @@
* storage volume.
*/
int cryptfs_revert_ext_volume(const char* label) {
- return delete_crypto_blk_dev((char*) label);
+ return delete_crypto_blk_dev((char*)label);
}
-int cryptfs_crypto_complete(void)
-{
- return do_crypto_complete("/data");
+int cryptfs_crypto_complete(void) {
+ return do_crypto_complete("/data");
}
-int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr)
-{
+int check_unmounted_and_get_ftr(struct crypt_mnt_ftr* crypt_ftr) {
char encrypted_state[PROPERTY_VALUE_MAX];
property_get("ro.crypto.state", encrypted_state, "");
- if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
- SLOGE("encrypted fs already validated or not running with encryption,"
- " aborting");
+ if (master_key_saved || strcmp(encrypted_state, "encrypted")) {
+ SLOGE(
+ "encrypted fs already validated or not running with encryption,"
+ " aborting");
return -1;
}
@@ -1935,10 +1938,9 @@
return 0;
}
-int cryptfs_check_passwd(const char *passwd)
-{
+int cryptfs_check_passwd(const char* passwd) {
SLOGI("cryptfs_check_passwd");
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
SLOGE("cryptfs_check_passwd not valid for file encryption");
return -1;
}
@@ -1952,8 +1954,7 @@
return rc;
}
- rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
- DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
+ rc = test_mount_encrypted_fs(&crypt_ftr, passwd, DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
if (rc) {
SLOGE("Password did not match");
return rc;
@@ -1965,8 +1966,8 @@
// First, we must delete the crypto block device that
// test_mount_encrypted_fs leaves behind as a side effect
delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
- rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
- DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
+ rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD, DATA_MNT_POINT,
+ CRYPTO_BLOCK_DEVICE);
if (rc) {
SLOGE("Default password did not match on reboot encryption");
return rc;
@@ -1992,15 +1993,14 @@
return rc;
}
-int cryptfs_verify_passwd(const char *passwd)
-{
+int cryptfs_verify_passwd(const char* passwd) {
struct crypt_mnt_ftr crypt_ftr;
unsigned char decrypted_master_key[MAX_KEY_LEN];
char encrypted_state[PROPERTY_VALUE_MAX];
int rc;
property_get("ro.crypto.state", encrypted_state, "");
- if (strcmp(encrypted_state, "encrypted") ) {
+ if (strcmp(encrypted_state, "encrypted")) {
SLOGE("device not encrypted, aborting");
return -2;
}
@@ -2043,8 +2043,7 @@
* Presumably, at a minimum, the caller will update the
* filesystem size and crypto_type_name after calling this function.
*/
-static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
-{
+static int cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr* ftr) {
off64_t off;
memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
@@ -2055,17 +2054,17 @@
ftr->keysize = cryptfs_get_keysize();
switch (keymaster_check_compatibility()) {
- case 1:
- ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
- break;
+ case 1:
+ ftr->kdf_type = KDF_SCRYPT_KEYMASTER;
+ break;
- case 0:
- ftr->kdf_type = KDF_SCRYPT;
- break;
+ case 0:
+ ftr->kdf_type = KDF_SCRYPT;
+ break;
- default:
- SLOGE("keymaster_check_compatibility failed");
- return -1;
+ default:
+ SLOGE("keymaster_check_compatibility failed");
+ return -1;
}
get_device_scrypt_params(ftr);
@@ -2073,8 +2072,7 @@
ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
if (get_crypt_ftr_info(NULL, &off) == 0) {
ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
- ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
- ftr->persist_data_size;
+ ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET + ftr->persist_data_size;
}
return 0;
@@ -2082,9 +2080,8 @@
#define FRAMEWORK_BOOT_WAIT 60
-static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf)
-{
- int fd = open(filename, O_RDONLY|O_CLOEXEC);
+static int cryptfs_SHA256_fileblock(const char* filename, __le8* buf) {
+ int fd = open(filename, O_RDONLY | O_CLOEXEC);
if (fd == -1) {
SLOGE("Error opening file %s", filename);
return -1;
@@ -2110,7 +2107,7 @@
static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
char* real_blkdev, int previously_encrypted_upto) {
- off64_t cur_encryption_done=0, tot_encryption_size=0;
+ off64_t cur_encryption_done = 0, tot_encryption_size = 0;
int rc = -1;
/* The size of the userdata partition, and add in the vold volumes below */
@@ -2144,19 +2141,19 @@
}
int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
- char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
+ char crypto_blkdev[MAXPATHLEN];
+ std::string real_blkdev;
unsigned char decrypted_master_key[MAX_KEY_LEN];
- int rc=-1, i;
+ int rc = -1, i;
struct crypt_mnt_ftr crypt_ftr;
- struct crypt_persist_data *pdata;
+ struct crypt_persist_data* pdata;
char encrypted_state[PROPERTY_VALUE_MAX];
- char lockid[32] = { 0 };
- char key_loc[PROPERTY_VALUE_MAX];
+ char lockid[32] = {0};
+ std::string key_loc;
int num_vols;
off64_t previously_encrypted_upto = 0;
bool rebootEncryption = false;
bool onlyCreateHeader = false;
- int fd = -1;
if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
@@ -2195,30 +2192,20 @@
goto error_unencrypted;
}
- // TODO refactor fs_mgr_get_crypt_info to get both in one call
- fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
- fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
+ get_crypt_info(&key_loc, &real_blkdev);
/* Get the size of the real block device */
- fd = open(real_blkdev, O_RDONLY|O_CLOEXEC);
- if (fd == -1) {
- SLOGE("Cannot open block device %s\n", real_blkdev);
+ uint64_t nr_sec;
+ if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
+ SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
goto error_unencrypted;
}
- unsigned long nr_sec;
- get_blkdev_size(fd, &nr_sec);
- if (nr_sec == 0) {
- SLOGE("Cannot get size of block device %s\n", real_blkdev);
- goto error_unencrypted;
- }
- close(fd);
/* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
- if (!strcmp(key_loc, KEY_IN_FOOTER)) {
- unsigned int fs_size_sec, max_fs_size_sec;
- fs_size_sec = get_fs_size(real_blkdev);
- if (fs_size_sec == 0)
- fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
+ if (key_loc == KEY_IN_FOOTER) {
+ uint64_t fs_size_sec, max_fs_size_sec;
+ fs_size_sec = get_fs_size(real_blkdev.c_str());
+ if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
@@ -2232,7 +2219,7 @@
* device to sleep on us. We'll grab a partial wakelock, and if the UI
* wants to keep the screen on, it can grab a full wakelock.
*/
- snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
+ snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
/* The init files are setup to stop the class main and late start when
@@ -2291,9 +2278,8 @@
goto error_shutting_down;
}
- if (!strcmp(key_loc, KEY_IN_FOOTER)) {
- crypt_ftr.fs_size = nr_sec
- - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
+ if (key_loc == KEY_IN_FOOTER) {
+ crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
} else {
crypt_ftr.fs_size = nr_sec;
}
@@ -2307,7 +2293,8 @@
crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
}
crypt_ftr.crypt_type = crypt_type;
- strlcpy((char *)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(), MAX_CRYPTO_TYPE_NAME_LEN);
+ strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
+ MAX_CRYPTO_TYPE_NAME_LEN);
/* Make an encrypted master key */
if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
@@ -2321,8 +2308,8 @@
unsigned char fake_master_key[MAX_KEY_LEN];
unsigned char encrypted_fake_master_key[MAX_KEY_LEN];
memset(fake_master_key, 0, sizeof(fake_master_key));
- encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
- encrypted_fake_master_key, &crypt_ftr);
+ encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key, encrypted_fake_master_key,
+ &crypt_ftr);
}
/* Write the key to the end of the partition */
@@ -2332,11 +2319,11 @@
* If none, create a valid empty table and save that.
*/
if (!persist_data) {
- pdata = (crypt_persist_data *)malloc(CRYPT_PERSIST_DATA_SIZE);
- if (pdata) {
- init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
- persist_data = pdata;
- }
+ pdata = (crypt_persist_data*)malloc(CRYPT_PERSIST_DATA_SIZE);
+ if (pdata) {
+ init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
+ persist_data = pdata;
+ }
}
if (persist_data) {
save_persistent_data();
@@ -2361,7 +2348,7 @@
}
decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
- create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
+ create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), crypto_blkdev,
CRYPTO_BLOCK_DEVICE, 0);
/* If we are continuing, check checksums match */
@@ -2370,22 +2357,21 @@
__le8 hash_first_block[SHA256_DIGEST_LENGTH];
rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
- if (!rc && memcmp(hash_first_block, crypt_ftr.hash_first_block,
- sizeof(hash_first_block)) != 0) {
+ if (!rc &&
+ memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
SLOGE("Checksums do not match - trigger wipe");
rc = -1;
}
}
if (!rc) {
- rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
+ rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev.data(),
previously_encrypted_upto);
}
/* Calculate checksum if we are not finished */
if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
- rc = cryptfs_SHA256_fileblock(crypto_blkdev,
- crypt_ftr.hash_first_block);
+ rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
if (rc) {
SLOGE("Error calculating checksum for continuing encryption");
rc = -1;
@@ -2395,7 +2381,7 @@
/* Undo the dm-crypt mapping whether we succeed or not */
delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
- if (! rc) {
+ if (!rc) {
/* Success */
crypt_ftr.flags &= ~CRYPT_INCONSISTENT_STATE;
@@ -2443,8 +2429,7 @@
SLOGE("encryption failed - rebooting into recovery to wipe data\n");
std::string err;
const std::vector<std::string> options = {
- "--wipe_data\n--reason=cryptfs_enable_internal\n"
- };
+ "--wipe_data\n--reason=cryptfs_enable_internal\n"};
if (!write_bootloader_message(options, &err)) {
SLOGE("could not write bootloader message: %s", err.c_str());
}
@@ -2477,7 +2462,9 @@
* but the framework is stopped and not restarted to show the error, so it's up to
* vold to restart the system.
*/
- SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
+ SLOGE(
+ "Error enabling encryption after framework is shutdown, no data changed, restarting "
+ "system");
cryptfs_reboot(RebootType::reboot);
/* shouldn't get here */
@@ -2496,9 +2483,8 @@
return cryptfs_enable_internal(CRYPT_TYPE_DEFAULT, DEFAULT_PASSWORD, no_ui);
}
-int cryptfs_changepw(int crypt_type, const char *newpw)
-{
- if (e4crypt_is_native()) {
+int cryptfs_changepw(int crypt_type, const char* newpw) {
+ if (fscrypt_is_native()) {
SLOGE("cryptfs_changepw not valid for file encryption");
return -1;
}
@@ -2525,12 +2511,8 @@
crypt_ftr.crypt_type = crypt_type;
- rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD
- : newpw,
- crypt_ftr.salt,
- saved_master_key,
- crypt_ftr.master_key,
- &crypt_ftr);
+ rc = encrypt_master_key(crypt_type == CRYPT_TYPE_DEFAULT ? DEFAULT_PASSWORD : newpw,
+ crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
if (rc) {
SLOGE("Encrypt master key failed: %d", rc);
return -1;
@@ -2544,28 +2526,28 @@
static unsigned int persist_get_max_entries(int encrypted) {
struct crypt_mnt_ftr crypt_ftr;
unsigned int dsize;
- unsigned int max_persistent_entries;
/* If encrypted, use the values from the crypt_ftr, otherwise
* use the values for the current spec.
*/
if (encrypted) {
if (get_crypt_ftr_and_key(&crypt_ftr)) {
- return -1;
+ /* Something is wrong, assume no space for entries */
+ return 0;
}
dsize = crypt_ftr.persist_data_size;
} else {
dsize = CRYPT_PERSIST_DATA_SIZE;
}
- max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
- sizeof(struct crypt_persist_entry);
-
- return max_persistent_entries;
+ if (dsize > sizeof(struct crypt_persist_data)) {
+ return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
+ } else {
+ return 0;
+ }
}
-static int persist_get_key(const char *fieldname, char *value)
-{
+static int persist_get_key(const char* fieldname, char* value) {
unsigned int i;
if (persist_data == NULL) {
@@ -2582,8 +2564,7 @@
return -1;
}
-static int persist_set_key(const char *fieldname, const char *value, int encrypted)
-{
+static int persist_set_key(const char* fieldname, const char* value, int encrypted) {
unsigned int i;
unsigned int num;
unsigned int max_persistent_entries;
@@ -2621,7 +2602,7 @@
* Test if key is part of the multi-entry (field, index) sequence. Return non-zero if key is in the
* sequence and its index is greater than or equal to index. Return 0 otherwise.
*/
-int match_multi_entry(const char *key, const char *field, unsigned index) {
+int match_multi_entry(const char* key, const char* field, unsigned index) {
std::string key_ = key;
std::string field_ = field;
@@ -2648,8 +2629,7 @@
* and PERSIST_DEL_KEY_ERROR_OTHER if error occurs.
*
*/
-static int persist_del_keys(const char *fieldname, unsigned index)
-{
+static int persist_del_keys(const char* fieldname, unsigned index) {
unsigned int i;
unsigned int j;
unsigned int num;
@@ -2660,7 +2640,7 @@
num = persist_data->persist_valid_entries;
- j = 0; // points to the end of non-deleted entries.
+ j = 0; // points to the end of non-deleted entries.
// Filter out to-be-deleted entries in place.
for (i = 0; i < num; i++) {
if (!match_multi_entry(persist_data->persist_entry[i].key, fieldname, index)) {
@@ -2680,8 +2660,7 @@
}
}
-static int persist_count_keys(const char *fieldname)
-{
+static int persist_count_keys(const char* fieldname) {
unsigned int i;
unsigned int count;
@@ -2700,9 +2679,8 @@
}
/* Return the value of the specified field. */
-int cryptfs_getfield(const char *fieldname, char *value, int len)
-{
- if (e4crypt_is_native()) {
+int cryptfs_getfield(const char* fieldname, char* value, int len) {
+ if (fscrypt_is_native()) {
SLOGE("Cannot get field when file encrypted");
return -1;
}
@@ -2729,7 +2707,7 @@
// stitch them back together.
if (!persist_get_key(fieldname, temp_value)) {
// We found it, copy it to the caller's buffer and keep going until all entries are read.
- if (strlcpy(value, temp_value, len) >= (unsigned) len) {
+ if (strlcpy(value, temp_value, len) >= (unsigned)len) {
// value too small
rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
goto out;
@@ -2738,7 +2716,7 @@
for (i = 1; /* break explicitly */; i++) {
if (snprintf(temp_field, sizeof(temp_field), "%s_%d", fieldname, i) >=
- (int) sizeof(temp_field)) {
+ (int)sizeof(temp_field)) {
// If the fieldname is very long, we stop as soon as it begins to overflow the
// maximum field length. At this point we have in fact fully read out the original
// value because cryptfs_setfield would not allow fields with longer names to be
@@ -2746,11 +2724,11 @@
break;
}
if (!persist_get_key(temp_field, temp_value)) {
- if (strlcat(value, temp_value, len) >= (unsigned)len) {
- // value too small.
- rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
- goto out;
- }
+ if (strlcat(value, temp_value, len) >= (unsigned)len) {
+ // value too small.
+ rc = CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL;
+ goto out;
+ }
} else {
// Exhaust all entries.
break;
@@ -2766,9 +2744,8 @@
}
/* Set the value of the specified field. */
-int cryptfs_setfield(const char *fieldname, const char *value)
-{
- if (e4crypt_is_native()) {
+int cryptfs_setfield(const char* fieldname, const char* value) {
+ if (fscrypt_is_native()) {
SLOGE("Cannot set field when file encrypted");
return -1;
}
@@ -2791,7 +2768,7 @@
}
property_get("ro.crypto.state", encrypted_state, "");
- if (!strcmp(encrypted_state, "encrypted") ) {
+ if (!strcmp(encrypted_state, "encrypted")) {
encrypted = 1;
}
@@ -2860,14 +2837,14 @@
* On success trigger next init phase and return 0.
* Currently do not handle failure - see TODO below.
*/
-int cryptfs_mount_default_encrypted(void)
-{
+int cryptfs_mount_default_encrypted(void) {
int crypt_type = cryptfs_get_password_type();
if (crypt_type < 0 || crypt_type > CRYPT_TYPE_MAX_TYPE) {
SLOGE("Bad crypt type - error");
} else if (crypt_type != CRYPT_TYPE_DEFAULT) {
- SLOGD("Password is not default - "
- "starting min framework to prompt");
+ SLOGD(
+ "Password is not default - "
+ "starting min framework to prompt");
property_set("vold.decrypt", "trigger_restart_min_framework");
return 0;
} else if (cryptfs_check_passwd(DEFAULT_PASSWORD) == 0) {
@@ -2887,9 +2864,8 @@
/* Returns type of the password, default, pattern, pin or password.
*/
-int cryptfs_get_password_type(void)
-{
- if (e4crypt_is_native()) {
+int cryptfs_get_password_type(void) {
+ if (fscrypt_is_native()) {
SLOGE("cryptfs_get_password_type not valid for file encryption");
return -1;
}
@@ -2908,9 +2884,8 @@
return crypt_ftr.crypt_type;
}
-const char* cryptfs_get_password()
-{
- if (e4crypt_is_native()) {
+const char* cryptfs_get_password() {
+ if (fscrypt_is_native()) {
SLOGE("cryptfs_get_password not valid for file encryption");
return 0;
}
@@ -2925,8 +2900,7 @@
}
}
-void cryptfs_clear_password()
-{
+void cryptfs_clear_password() {
if (password) {
size_t len = strlen(password);
memset(password, 0, len);
@@ -2936,8 +2910,7 @@
}
}
-int cryptfs_isConvertibleToFBE()
-{
- struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
- return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
+int cryptfs_isConvertibleToFBE() {
+ auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
+ return entry && entry->fs_mgr_flags.force_fde_or_fbe;
}
diff --git a/cryptfs.h b/cryptfs.h
index d6c7dc5..692d7ee 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -29,8 +29,10 @@
* partition.
*/
+#include <linux/types.h>
#include <stdbool.h>
#include <stdint.h>
+
#include <cutils/properties.h>
/* The current cryptfs version */
@@ -49,32 +51,39 @@
/* definitions of flags in the structure below */
#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
-#define CRYPT_ENCRYPTION_IN_PROGRESS 0x2 /* Encryption partially completed,
- encrypted_upto valid*/
-#define CRYPT_INCONSISTENT_STATE 0x4 /* Set when starting encryption, clear when
- exit cleanly, either through success or
- correctly marked partial encryption */
-#define CRYPT_DATA_CORRUPT 0x8 /* Set when encryption is fine, but the
- underlying volume is corrupt */
-#define CRYPT_FORCE_ENCRYPTION 0x10 /* Set when it is time to encrypt this
- volume on boot. Everything in this
- structure is set up correctly as
- though device is encrypted except
- that the master key is encrypted with the
- default password. */
-#define CRYPT_FORCE_COMPLETE 0x20 /* Set when the above encryption cycle is
- complete. On next cryptkeeper entry, match
- the password. If it matches fix the master
- key and remove this flag. */
+#define CRYPT_ENCRYPTION_IN_PROGRESS \
+ 0x2 /* Encryption partially completed, \
+ encrypted_upto valid*/
+#define CRYPT_INCONSISTENT_STATE \
+ 0x4 /* Set when starting encryption, clear when \
+ exit cleanly, either through success or \
+ correctly marked partial encryption */
+#define CRYPT_DATA_CORRUPT \
+ 0x8 /* Set when encryption is fine, but the \
+ underlying volume is corrupt */
+#define CRYPT_FORCE_ENCRYPTION \
+ 0x10 /* Set when it is time to encrypt this \
+ volume on boot. Everything in this \
+ structure is set up correctly as \
+ though device is encrypted except \
+ that the master key is encrypted with the \
+ default password. */
+#define CRYPT_FORCE_COMPLETE \
+ 0x20 /* Set when the above encryption cycle is \
+ complete. On next cryptkeeper entry, match \
+ the password. If it matches fix the master \
+ key and remove this flag. */
/* Allowed values for type in the structure below */
-#define CRYPT_TYPE_PASSWORD 0 /* master_key is encrypted with a password
- * Must be zero to be compatible with pre-L
- * devices where type is always password.*/
-#define CRYPT_TYPE_DEFAULT 1 /* master_key is encrypted with default
- * password */
-#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
-#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
+#define CRYPT_TYPE_PASSWORD \
+ 0 /* master_key is encrypted with a password \
+ * Must be zero to be compatible with pre-L \
+ * devices where type is always password.*/
+#define CRYPT_TYPE_DEFAULT \
+ 1 /* master_key is encrypted with default \
+ * password */
+#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
+#define CRYPT_TYPE_PIN 3 /* master_key is encrypted with a pin */
#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
#define CRYPT_MNT_MAGIC 0xD0B5B1C4
@@ -90,78 +99,78 @@
#define KEYMASTER_BLOB_SIZE 2048
/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
-#define __le8 unsigned char
+#define __le8 unsigned char
#if !defined(SHA256_DIGEST_LENGTH)
#define SHA256_DIGEST_LENGTH 32
#endif
struct crypt_mnt_ftr {
- __le32 magic; /* See above */
- __le16 major_version;
- __le16 minor_version;
- __le32 ftr_size; /* in bytes, not including key following */
- __le32 flags; /* See above */
- __le32 keysize; /* in bytes */
- __le32 crypt_type; /* how master_key is encrypted. Must be a
- * CRYPT_TYPE_XXX value */
- __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
- __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
- mount, set to 0 on successful mount */
- unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
- needed to decrypt this
- partition, null terminated */
- __le32 spare2; /* ignored */
- unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
- unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
- __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
- * on device with that info, either the footer of the
- * real_blkdevice or the metadata partition. */
+ __le32 magic; /* See above */
+ __le16 major_version;
+ __le16 minor_version;
+ __le32 ftr_size; /* in bytes, not including key following */
+ __le32 flags; /* See above */
+ __le32 keysize; /* in bytes */
+ __le32 crypt_type; /* how master_key is encrypted. Must be a
+ * CRYPT_TYPE_XXX value */
+ __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
+ __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
+ mount, set to 0 on successful mount */
+ unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
+ needed to decrypt this
+ partition, null terminated */
+ __le32 spare2; /* ignored */
+ unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
+ unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
+ __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
+ * on device with that info, either the footer of the
+ * real_blkdevice or the metadata partition. */
- __le32 persist_data_size; /* The number of bytes allocated to each copy of the
- * persistent data table*/
+ __le32 persist_data_size; /* The number of bytes allocated to each copy of the
+ * persistent data table*/
- __le8 kdf_type; /* The key derivation function used. */
+ __le8 kdf_type; /* The key derivation function used. */
- /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
- __le8 N_factor; /* (1 << N) */
- __le8 r_factor; /* (1 << r) */
- __le8 p_factor; /* (1 << p) */
- __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
- we have to stop (e.g. power low) this is the last
- encrypted 512 byte sector.*/
- __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
- set, hash of first block, used
- to validate before continuing*/
+ /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
+ __le8 N_factor; /* (1 << N) */
+ __le8 r_factor; /* (1 << r) */
+ __le8 p_factor; /* (1 << p) */
+ __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
+ we have to stop (e.g. power low) this is the last
+ encrypted 512 byte sector.*/
+ __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
+ set, hash of first block, used
+ to validate before continuing*/
- /* key_master key, used to sign the derived key which is then used to generate
- * the intermediate key
- * This key should be used for no other purposes! We use this key to sign unpadded
- * data, which is acceptable but only if the key is not reused elsewhere. */
- __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
- __le32 keymaster_blob_size;
+ /* key_master key, used to sign the derived key which is then used to generate
+ * the intermediate key
+ * This key should be used for no other purposes! We use this key to sign unpadded
+ * data, which is acceptable but only if the key is not reused elsewhere. */
+ __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
+ __le32 keymaster_blob_size;
- /* Store scrypt of salted intermediate key. When decryption fails, we can
- check if this matches, and if it does, we know that the problem is with the
- drive, and there is no point in asking the user for more passwords.
+ /* Store scrypt of salted intermediate key. When decryption fails, we can
+ check if this matches, and if it does, we know that the problem is with the
+ drive, and there is no point in asking the user for more passwords.
- Note that if any part of this structure is corrupt, this will not match and
- we will continue to believe the user entered the wrong password. In that
- case the only solution is for the user to enter a password enough times to
- force a wipe.
+ Note that if any part of this structure is corrupt, this will not match and
+ we will continue to believe the user entered the wrong password. In that
+ case the only solution is for the user to enter a password enough times to
+ force a wipe.
- Note also that there is no need to worry about migration. If this data is
- wrong, we simply won't recognise a right password, and will continue to
- prompt. On the first password change, this value will be populated and
- then we will be OK.
- */
- unsigned char scrypted_intermediate_key[SCRYPT_LEN];
+ Note also that there is no need to worry about migration. If this data is
+ wrong, we simply won't recognise a right password, and will continue to
+ prompt. On the first password change, this value will be populated and
+ then we will be OK.
+ */
+ unsigned char scrypted_intermediate_key[SCRYPT_LEN];
- /* sha of this structure with this element set to zero
- Used when encrypting on reboot to validate structure before doing something
- fatal
- */
- unsigned char sha256[SHA256_DIGEST_LENGTH];
+ /* sha of this structure with this element set to zero
+ Used when encrypting on reboot to validate structure before doing something
+ fatal
+ */
+ unsigned char sha256[SHA256_DIGEST_LENGTH];
};
/* Persistant data that should be available before decryption.
@@ -178,49 +187,49 @@
* and higher crypt_mnt_ftr structures.
*/
struct crypt_persist_entry {
- char key[PROPERTY_KEY_MAX];
- char val[PROPERTY_VALUE_MAX];
+ char key[PROPERTY_KEY_MAX];
+ char val[PROPERTY_VALUE_MAX];
};
/* Should be exactly 4K in size */
struct crypt_persist_data {
- __le32 persist_magic;
- __le32 persist_valid_entries;
- __le32 persist_spare[30];
- struct crypt_persist_entry persist_entry[0];
+ __le32 persist_magic;
+ __le32 persist_valid_entries;
+ __le32 persist_spare[30];
+ struct crypt_persist_entry persist_entry[0];
};
#define DATA_MNT_POINT "/data"
/* Return values for cryptfs_crypto_complete */
-#define CRYPTO_COMPLETE_NOT_ENCRYPTED 1
-#define CRYPTO_COMPLETE_ENCRYPTED 0
-#define CRYPTO_COMPLETE_BAD_METADATA (-1)
-#define CRYPTO_COMPLETE_PARTIAL (-2)
-#define CRYPTO_COMPLETE_INCONSISTENT (-3)
-#define CRYPTO_COMPLETE_CORRUPT (-4)
+#define CRYPTO_COMPLETE_NOT_ENCRYPTED 1
+#define CRYPTO_COMPLETE_ENCRYPTED 0
+#define CRYPTO_COMPLETE_BAD_METADATA (-1)
+#define CRYPTO_COMPLETE_PARTIAL (-2)
+#define CRYPTO_COMPLETE_INCONSISTENT (-3)
+#define CRYPTO_COMPLETE_CORRUPT (-4)
/* Return values for cryptfs_enable_inplace*() */
#define ENABLE_INPLACE_OK 0
#define ENABLE_INPLACE_ERR_OTHER (-1)
-#define ENABLE_INPLACE_ERR_DEV (-2) /* crypto_blkdev issue */
+#define ENABLE_INPLACE_ERR_DEV (-2) /* crypto_blkdev issue */
/* Return values for cryptfs_getfield */
-#define CRYPTO_GETFIELD_OK 0
-#define CRYPTO_GETFIELD_ERROR_NO_FIELD (-1)
-#define CRYPTO_GETFIELD_ERROR_OTHER (-2)
+#define CRYPTO_GETFIELD_OK 0
+#define CRYPTO_GETFIELD_ERROR_NO_FIELD (-1)
+#define CRYPTO_GETFIELD_ERROR_OTHER (-2)
#define CRYPTO_GETFIELD_ERROR_BUF_TOO_SMALL (-3)
/* Return values for cryptfs_setfield */
-#define CRYPTO_SETFIELD_OK 0
-#define CRYPTO_SETFIELD_ERROR_OTHER (-1)
+#define CRYPTO_SETFIELD_OK 0
+#define CRYPTO_SETFIELD_ERROR_OTHER (-1)
#define CRYPTO_SETFIELD_ERROR_FIELD_TOO_LONG (-2)
#define CRYPTO_SETFIELD_ERROR_VALUE_TOO_LONG (-3)
/* Return values for persist_del_key */
-#define PERSIST_DEL_KEY_OK 0
-#define PERSIST_DEL_KEY_ERROR_OTHER (-1)
-#define PERSIST_DEL_KEY_ERROR_NO_FIELD (-2)
+#define PERSIST_DEL_KEY_OK 0
+#define PERSIST_DEL_KEY_ERROR_OTHER (-1)
+#define PERSIST_DEL_KEY_ERROR_NO_FIELD (-2)
int match_multi_entry(const char* key, const char* field, unsigned index);
int wait_and_unmount(const char* mountpoint, bool kill);
diff --git a/fs/Exfat.cpp b/fs/Exfat.cpp
index 5c15075..c624eb9 100644
--- a/fs/Exfat.cpp
+++ b/fs/Exfat.cpp
@@ -43,7 +43,7 @@
cmd.push_back(kFsckPath);
cmd.push_back(source);
- int rc = ForkExecvp(cmd, sFsckUntrustedContext);
+ int rc = ForkExecvp(cmd, nullptr, sFsckUntrustedContext);
if (rc == 0) {
LOG(INFO) << "Check OK";
return 0;
diff --git a/fs/Ext4.cpp b/fs/Ext4.cpp
index 89b8414..0059233 100644
--- a/fs/Ext4.cpp
+++ b/fs/Ext4.cpp
@@ -14,40 +14,34 @@
* limitations under the License.
*/
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <errno.h>
-#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
-#include <vector>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
#include <string>
+#include <vector>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/types.h>
#include <sys/mman.h>
#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include <sys/wait.h>
#include <linux/kdev_t.h>
-#define LOG_TAG "Vold"
-
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
-#include <cutils/log.h>
#include <cutils/properties.h>
-#include <ext4_utils/ext4_crypt.h>
+#include <fscrypt/fscrypt.h>
#include <logwrap/logwrap.h>
#include <selinux/selinux.h>
#include "Ext4.h"
-#include "Ext4Crypt.h"
+#include "FsCrypt.h"
#include "Utils.h"
#include "VoldUtil.h"
@@ -62,9 +56,8 @@
static const char* kFsckPath = "/system/bin/e2fsck";
bool IsSupported() {
- return access(kMkfsPath, X_OK) == 0
- && access(kFsckPath, X_OK) == 0
- && IsFilesystemSupported("ext4");
+ return access(kMkfsPath, X_OK) == 0 && access(kFsckPath, X_OK) == 0 &&
+ IsFilesystemSupported("ext4");
}
status_t Check(const std::string& source, const std::string& target) {
@@ -77,7 +70,7 @@
int status;
int ret;
long tmpmnt_flags = MS_NOATIME | MS_NOEXEC | MS_NOSUID;
- char *tmpmnt_opts = (char*) "nomblk_io_submit,errors=remount-ro";
+ char* tmpmnt_opts = (char*)"nomblk_io_submit,errors=remount-ro";
/*
* First try to mount and unmount the filesystem. We do this because
@@ -102,7 +95,8 @@
if (result == 0) {
break;
}
- ALOGW("%s(): umount(%s)=%d: %s\n", __func__, c_target, result, strerror(errno));
+ LOG(WARNING) << __func__ << "(): umount(" << c_target << ")=" << result << ": "
+ << strerror(errno);
sleep(1);
}
}
@@ -112,10 +106,10 @@
* (e.g. recent SDK system images). Detect these and skip the check.
*/
if (access(kFsckPath, X_OK)) {
- ALOGD("Not running %s on %s (executable not in system image)\n",
- kFsckPath, c_source);
+ LOG(DEBUG) << "Not running " << kFsckPath << " on " << c_source
+ << " (executable not in system image)";
} else {
- ALOGD("Running %s on %s\n", kFsckPath, c_source);
+ LOG(DEBUG) << "Running " << kFsckPath << " on " << c_source;
std::vector<std::string> cmd;
cmd.push_back(kFsckPath);
@@ -123,14 +117,14 @@
cmd.push_back(c_source);
// ext4 devices are currently always trusted
- return ForkExecvp(cmd, sFsckContext);
+ return ForkExecvp(cmd, nullptr, sFsckContext);
}
return 0;
}
-status_t Mount(const std::string& source, const std::string& target, bool ro,
- bool remount, bool executable) {
+status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount,
+ bool executable) {
int rc;
unsigned long flags;
@@ -164,8 +158,7 @@
return ForkExecvp(cmd);
}
-status_t Format(const std::string& source, unsigned long numSectors,
- const std::string& target) {
+status_t Format(const std::string& source, unsigned long numSectors, const std::string& target) {
std::vector<std::string> cmd;
cmd.push_back(kMkfsPath);
@@ -182,7 +175,7 @@
if (android::base::GetBoolProperty("vold.has_quota", false)) {
options += ",quota";
}
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
options += ",encrypt";
}
diff --git a/fs/Ext4.h b/fs/Ext4.h
index f78dc95..329f302 100644
--- a/fs/Ext4.h
+++ b/fs/Ext4.h
@@ -28,10 +28,9 @@
bool IsSupported();
status_t Check(const std::string& source, const std::string& target);
-status_t Mount(const std::string& source, const std::string& target, bool ro,
- bool remount, bool executable);
-status_t Format(const std::string& source, unsigned long numSectors,
- const std::string& target);
+status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount,
+ bool executable);
+status_t Format(const std::string& source, unsigned long numSectors, const std::string& target);
status_t Resize(const std::string& source, unsigned long numSectors);
} // namespace ext4
diff --git a/fs/F2fs.cpp b/fs/F2fs.cpp
index f24fd91..9517dc9 100644
--- a/fs/F2fs.cpp
+++ b/fs/F2fs.cpp
@@ -20,10 +20,10 @@
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
-#include <ext4_utils/ext4_crypt.h>
+#include <fscrypt/fscrypt.h>
-#include <vector>
#include <string>
+#include <vector>
#include <sys/mount.h>
@@ -37,9 +37,8 @@
static const char* kFsckPath = "/system/bin/fsck.f2fs";
bool IsSupported() {
- return access(kMkfsPath, X_OK) == 0
- && access(kFsckPath, X_OK) == 0
- && IsFilesystemSupported("f2fs");
+ return access(kMkfsPath, X_OK) == 0 && access(kFsckPath, X_OK) == 0 &&
+ IsFilesystemSupported("f2fs");
}
status_t Check(const std::string& source) {
@@ -49,7 +48,7 @@
cmd.push_back(source);
// f2fs devices are currently always trusted
- return ForkExecvp(cmd, sFsckContext);
+ return ForkExecvp(cmd, nullptr, sFsckContext);
}
status_t Mount(const std::string& source, const std::string& target) {
@@ -82,7 +81,7 @@
cmd.push_back("-O");
cmd.push_back("quota");
}
- if (e4crypt_is_native()) {
+ if (fscrypt_is_native()) {
cmd.push_back("-O");
cmd.push_back("encrypt");
}
diff --git a/fs/Vfat.cpp b/fs/Vfat.cpp
index 538178e..14c42d6 100644
--- a/fs/Vfat.cpp
+++ b/fs/Vfat.cpp
@@ -14,24 +14,21 @@
* limitations under the License.
*/
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <errno.h>
-#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/wait.h>
#include <linux/fs.h>
#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
#include <linux/kdev_t.h>
@@ -41,8 +38,8 @@
#include <logwrap/logwrap.h>
-#include "Vfat.h"
#include "Utils.h"
+#include "Vfat.h"
#include "VoldUtil.h"
using android::base::StringPrintf;
@@ -55,9 +52,8 @@
static const char* kFsckPath = "/system/bin/fsck_msdos";
bool IsSupported() {
- return access(kMkfsPath, X_OK) == 0
- && access(kFsckPath, X_OK) == 0
- && IsFilesystemSupported("vfat");
+ return access(kMkfsPath, X_OK) == 0 && access(kFsckPath, X_OK) == 0 &&
+ IsFilesystemSupported("vfat");
}
status_t Check(const std::string& source) {
@@ -71,7 +67,7 @@
cmd.push_back(source);
// Fat devices are currently always untrusted
- rc = ForkExecvp(cmd, sFsckUntrustedContext);
+ rc = ForkExecvp(cmd, nullptr, sFsckUntrustedContext);
if (rc < 0) {
LOG(ERROR) << "Filesystem check failed due to logwrap error";
@@ -79,43 +75,42 @@
return -1;
}
- switch(rc) {
- case 0:
- LOG(INFO) << "Filesystem check completed OK";
- return 0;
+ switch (rc) {
+ case 0:
+ LOG(INFO) << "Filesystem check completed OK";
+ return 0;
- case 2:
- LOG(ERROR) << "Filesystem check failed (not a FAT filesystem)";
- errno = ENODATA;
- return -1;
+ case 2:
+ LOG(ERROR) << "Filesystem check failed (not a FAT filesystem)";
+ errno = ENODATA;
+ return -1;
- case 4:
- if (pass++ <= 3) {
- LOG(WARNING) << "Filesystem modified - rechecking (pass " << pass << ")";
- continue;
- }
- LOG(ERROR) << "Failing check after too many rechecks";
- errno = EIO;
- return -1;
+ case 4:
+ if (pass++ <= 3) {
+ LOG(WARNING) << "Filesystem modified - rechecking (pass " << pass << ")";
+ continue;
+ }
+ LOG(ERROR) << "Failing check after too many rechecks";
+ errno = EIO;
+ return -1;
- case 8:
- LOG(ERROR) << "Filesystem check failed (no filesystem)";
- errno = ENODATA;
- return -1;
+ case 8:
+ LOG(ERROR) << "Filesystem check failed (no filesystem)";
+ errno = ENODATA;
+ return -1;
- default:
- LOG(ERROR) << "Filesystem check failed (unknown exit code " << rc << ")";
- errno = EIO;
- return -1;
+ default:
+ LOG(ERROR) << "Filesystem check failed (unknown exit code " << rc << ")";
+ errno = EIO;
+ return -1;
}
} while (0);
return 0;
}
-status_t Mount(const std::string& source, const std::string& target, bool ro,
- bool remount, bool executable, int ownerUid, int ownerGid, int permMask,
- bool createLost) {
+status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount,
+ bool executable, int ownerUid, int ownerGid, int permMask, bool createLost) {
int rc;
unsigned long flags;
@@ -128,9 +123,9 @@
flags |= (ro ? MS_RDONLY : 0);
flags |= (remount ? MS_REMOUNT : 0);
- auto mountData = android::base::StringPrintf(
- "utf8,uid=%d,gid=%d,fmask=%o,dmask=%o,shortname=mixed",
- ownerUid, ownerGid, permMask, permMask);
+ auto mountData =
+ android::base::StringPrintf("utf8,uid=%d,gid=%d,fmask=%o,dmask=%o,shortname=mixed",
+ ownerUid, ownerGid, permMask, permMask);
rc = mount(c_source, c_target, "vfat", flags, mountData.c_str());
@@ -159,12 +154,8 @@
status_t Format(const std::string& source, unsigned long numSectors) {
std::vector<std::string> cmd;
cmd.push_back(kMkfsPath);
- cmd.push_back("-F");
- cmd.push_back("32");
cmd.push_back("-O");
cmd.push_back("android");
- cmd.push_back("-c");
- cmd.push_back("64");
cmd.push_back("-A");
if (numSectors) {
diff --git a/fs/Vfat.h b/fs/Vfat.h
index 40be5f6..2030067 100644
--- a/fs/Vfat.h
+++ b/fs/Vfat.h
@@ -28,9 +28,8 @@
bool IsSupported();
status_t Check(const std::string& source);
-status_t Mount(const std::string& source, const std::string& target, bool ro,
- bool remount, bool executable, int ownerUid, int ownerGid, int permMask,
- bool createLost);
+status_t Mount(const std::string& source, const std::string& target, bool ro, bool remount,
+ bool executable, int ownerUid, int ownerGid, int permMask, bool createLost);
status_t Format(const std::string& source, unsigned long numSectors);
} // namespace vfat
diff --git a/hash.h b/hash.h
deleted file mode 100644
index 3b483f1..0000000
--- a/hash.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (c) 1999 Kungliga Tekniska Högskolan
- * (Royal Institute of Technology, Stockholm, Sweden).
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * 3. Neither the name of KTH nor the names of its contributors may be
- * used to endorse or promote products derived from this software without
- * specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
- * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
-
-/* $Heimdal: hash.h,v 1.1 1999/03/22 19:16:25 joda Exp $
- $NetBSD: hash.h,v 1.1.1.3 2002/09/12 12:41:42 joda Exp $ */
-
-/* stuff in common between md4, md5, and sha1 */
-
-#ifndef __hash_h__
-#define __hash_h__
-
-#include <stdlib.h>
-#include <string.h>
-
-#ifndef min
-#define min(a,b) (((a)>(b))?(b):(a))
-#endif
-
-/* Vector Crays doesn't have a good 32-bit type, or more precisely,
- int32_t as defined by <bind/bitypes.h> isn't 32 bits, and we don't
- want to depend in being able to redefine this type. To cope with
- this we have to clamp the result in some places to [0,2^32); no
- need to do this on other machines. Did I say this was a mess?
- */
-
-#ifdef _CRAY
-#define CRAYFIX(X) ((X) & 0xffffffff)
-#else
-#define CRAYFIX(X) (X)
-#endif
-
-static inline u_int32_t
-cshift (u_int32_t x, unsigned int n)
-{
- x = CRAYFIX(x);
- return CRAYFIX((x << n) | (x >> (32 - n)));
-}
-
-#endif /* __hash_h__ */
diff --git a/main.cpp b/main.cpp
index 5525e85..27a701b 100644
--- a/main.cpp
+++ b/main.cpp
@@ -16,57 +16,58 @@
#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
-#include "model/Disk.h"
-#include "VolumeManager.h"
#include "NetlinkManager.h"
#include "VoldNativeService.h"
#include "VoldUtil.h"
+#include "VolumeManager.h"
#include "cryptfs.h"
+#include "model/Disk.h"
#include "sehandle.h"
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <cutils/klog.h>
+#include <hidl/HidlTransportSupport.h>
#include <utils/Trace.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fs_mgr.h>
+#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
-#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
-#include <getopt.h>
-#include <fcntl.h>
-#include <dirent.h>
-#include <fs_mgr.h>
static int process_config(VolumeManager* vm, bool* has_adoptable, bool* has_quota,
bool* has_reserved);
-static void coldboot(const char *path);
+static void coldboot(const char* path);
static void parse_args(int argc, char** argv);
-struct selabel_handle *sehandle;
+struct selabel_handle* sehandle;
using android::base::StringPrintf;
+using android::fs_mgr::ReadDefaultFstab;
int main(int argc, char** argv) {
atrace_set_tracing_enabled(false);
- setenv("ANDROID_LOG_TAGS", "*:v", 1);
+ setenv("ANDROID_LOG_TAGS", "*:d", 1); // Do not submit with verbose logs enabled
android::base::InitLogging(argv, android::base::LogdLogger(android::base::SYSTEM));
LOG(INFO) << "Vold 3.0 (the awakening) firing up";
ATRACE_BEGIN("main");
+ LOG(DEBUG) << "Detected support for:"
+ << (android::vold::IsFilesystemSupported("ext4") ? " ext4" : "")
+ << (android::vold::IsFilesystemSupported("f2fs") ? " f2fs" : "")
+ << (android::vold::IsFilesystemSupported("vfat") ? " vfat" : "");
- LOG(VERBOSE) << "Detected support for:"
- << (android::vold::IsFilesystemSupported("ext4") ? " ext4" : "")
- << (android::vold::IsFilesystemSupported("f2fs") ? " f2fs" : "")
- << (android::vold::IsFilesystemSupported("vfat") ? " vfat" : "");
-
- VolumeManager *vm;
- NetlinkManager *nm;
+ VolumeManager* vm;
+ NetlinkManager* nm;
parse_args(argc, argv);
@@ -108,6 +109,8 @@
PLOG(ERROR) << "Error reading configuration... continuing anyways";
}
+ android::hardware::configureRpcThreadpool(1, false /* callerWillJoin */);
+
ATRACE_BEGIN("VoldNativeService::start");
if (android::vold::VoldNativeService::start() != android::OK) {
LOG(ERROR) << "Unable to start VoldNativeService";
@@ -145,19 +148,21 @@
static void parse_args(int argc, char** argv) {
static struct option opts[] = {
- {"blkid_context", required_argument, 0, 'b' },
- {"blkid_untrusted_context", required_argument, 0, 'B' },
- {"fsck_context", required_argument, 0, 'f' },
- {"fsck_untrusted_context", required_argument, 0, 'F' },
+ {"blkid_context", required_argument, 0, 'b'},
+ {"blkid_untrusted_context", required_argument, 0, 'B'},
+ {"fsck_context", required_argument, 0, 'f'},
+ {"fsck_untrusted_context", required_argument, 0, 'F'},
};
int c;
while ((c = getopt_long(argc, argv, "", opts, nullptr)) != -1) {
switch (c) {
+ // clang-format off
case 'b': android::vold::sBlkidContext = optarg; break;
case 'B': android::vold::sBlkidUntrustedContext = optarg; break;
case 'f': android::vold::sFsckContext = optarg; break;
case 'F': android::vold::sFsckUntrustedContext = optarg; break;
+ // clang-format on
}
}
@@ -167,33 +172,30 @@
CHECK(android::vold::sFsckUntrustedContext != nullptr);
}
-static void do_coldboot(DIR *d, int lvl) {
- struct dirent *de;
+static void do_coldboot(DIR* d, int lvl) {
+ struct dirent* de;
int dfd, fd;
dfd = dirfd(d);
fd = openat(dfd, "uevent", O_WRONLY | O_CLOEXEC);
- if(fd >= 0) {
+ if (fd >= 0) {
write(fd, "add\n", 4);
close(fd);
}
- while((de = readdir(d))) {
- DIR *d2;
+ while ((de = readdir(d))) {
+ DIR* d2;
- if (de->d_name[0] == '.')
- continue;
+ if (de->d_name[0] == '.') continue;
- if (de->d_type != DT_DIR && lvl > 0)
- continue;
+ if (de->d_type != DT_DIR && lvl > 0) continue;
fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
- if(fd < 0)
- continue;
+ if (fd < 0) continue;
d2 = fdopendir(fd);
- if(d2 == 0)
+ if (d2 == 0)
close(fd);
else {
do_coldboot(d2, lvl + 1);
@@ -202,10 +204,10 @@
}
}
-static void coldboot(const char *path) {
+static void coldboot(const char* path) {
ATRACE_NAME("coldboot");
- DIR *d = opendir(path);
- if(d) {
+ DIR* d = opendir(path);
+ if (d) {
do_coldboot(d, 0);
closedir(d);
}
@@ -215,8 +217,7 @@
bool* has_reserved) {
ATRACE_NAME("process_config");
- fstab_default = fs_mgr_read_fstab_default();
- if (!fstab_default) {
+ if (!ReadDefaultFstab(&fstab_default)) {
PLOG(ERROR) << "Failed to open default fstab";
return -1;
}
@@ -225,36 +226,40 @@
*has_adoptable = false;
*has_quota = false;
*has_reserved = false;
- for (int i = 0; i < fstab_default->num_entries; i++) {
- auto rec = &fstab_default->recs[i];
- if (fs_mgr_is_quota(rec)) {
+ for (auto& entry : fstab_default) {
+ if (entry.fs_mgr_flags.quota) {
*has_quota = true;
}
- if (rec->reserved_size > 0) {
+ if (entry.reserved_size > 0) {
*has_reserved = true;
}
- if (fs_mgr_is_voldmanaged(rec)) {
- if (fs_mgr_is_nonremovable(rec)) {
+ /* Make sure logical partitions have an updated blk_device. */
+ if (entry.fs_mgr_flags.logical && !fs_mgr_update_logical_partition(&entry)) {
+ PLOG(FATAL) << "could not find logical partition " << entry.blk_device;
+ }
+
+ if (entry.fs_mgr_flags.vold_managed) {
+ if (entry.fs_mgr_flags.nonremovable) {
LOG(WARNING) << "nonremovable no longer supported; ignoring volume";
continue;
}
- std::string sysPattern(rec->blk_device);
- std::string nickname(rec->label);
+ std::string sysPattern(entry.blk_device);
+ std::string nickname(entry.label);
int flags = 0;
- if (fs_mgr_is_encryptable(rec)) {
+ if (entry.is_encryptable()) {
flags |= android::vold::Disk::Flags::kAdoptable;
*has_adoptable = true;
}
- if (fs_mgr_is_noemulatedsd(rec)
- || android::base::GetBoolProperty("vold.debug.default_primary", false)) {
+ if (entry.fs_mgr_flags.no_emulated_sd ||
+ android::base::GetBoolProperty("vold.debug.default_primary", false)) {
flags |= android::vold::Disk::Flags::kDefaultPrimary;
}
vm->addDiskSource(std::shared_ptr<VolumeManager::DiskSource>(
- new VolumeManager::DiskSource(sysPattern, nickname, flags)));
+ new VolumeManager::DiskSource(sysPattern, nickname, flags)));
}
}
return 0;
diff --git a/model/Disk.cpp b/model/Disk.cpp
index d7b19ac..b66c336 100644
--- a/model/Disk.cpp
+++ b/model/Disk.cpp
@@ -15,36 +15,36 @@
*/
#include "Disk.h"
-#include "PublicVolume.h"
+#include "FsCrypt.h"
#include "PrivateVolume.h"
+#include "PublicVolume.h"
#include "Utils.h"
#include "VolumeBase.h"
#include "VolumeManager.h"
-#include "Ext4Crypt.h"
#include <android-base/file.h>
#include <android-base/logging.h>
+#include <android-base/parseint.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
-#include <android-base/parseint.h>
-#include <ext4_utils/ext4_crypt.h>
+#include <fscrypt/fscrypt.h>
#include "cryptfs.h"
-#include <vector>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
-#include <sys/types.h>
+#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
-#include <sys/mount.h>
+#include <sys/types.h>
+#include <vector>
using android::base::ReadFileToString;
-using android::base::WriteStringToFile;
using android::base::StringPrintf;
+using android::base::WriteStringToFile;
namespace android {
namespace vold {
@@ -76,6 +76,8 @@
static const unsigned int kMajorBlockMmc = 179;
static const unsigned int kMajorBlockExperimentalMin = 240;
static const unsigned int kMajorBlockExperimentalMax = 254;
+static const unsigned int kMajorBlockDynamicMin = 234;
+static const unsigned int kMajorBlockDynamicMax = 512;
static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
@@ -110,14 +112,22 @@
* "ranchu", the device's sysfs path should end with "/block/vd[d-z]", etc.
* But just having a) and b) is enough for now.
*/
- return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin
- && major <= kMajorBlockExperimentalMax;
+ return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin &&
+ major <= kMajorBlockExperimentalMax;
}
-Disk::Disk(const std::string& eventPath, dev_t device,
- const std::string& nickname, int flags) :
- mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated(
- false), mJustPartitioned(false) {
+static bool isNvmeBlkDevice(unsigned int major, const std::string& sysPath) {
+ return sysPath.find("nvme") != std::string::npos && major >= kMajorBlockDynamicMin &&
+ major <= kMajorBlockDynamicMax;
+}
+
+Disk::Disk(const std::string& eventPath, dev_t device, const std::string& nickname, int flags)
+ : mDevice(device),
+ mSize(-1),
+ mNickname(nickname),
+ mFlags(flags),
+ mCreated(false),
+ mJustPartitioned(false) {
mId = StringPrintf("disk:%u,%u", major(device), minor(device));
mEventPath = eventPath;
mSysPath = StringPrintf("/sys/%s", eventPath.c_str());
@@ -143,7 +153,7 @@
return nullptr;
}
-void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) {
+void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) const {
for (const auto& vol : mVolumes) {
if (vol->getType() == type) {
list.push_back(vol->getId());
@@ -233,73 +243,84 @@
mSize = -1;
mLabel.clear();
- int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC);
- if (fd != -1) {
- if (ioctl(fd, BLKGETSIZE64, &mSize)) {
- mSize = -1;
- }
- close(fd);
+ if (GetBlockDevSize(mDevPath, &mSize) != OK) {
+ mSize = -1;
}
unsigned int majorId = major(mDevice);
switch (majorId) {
- case kMajorBlockLoop: {
- mLabel = "Virtual";
- break;
- }
- case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
- case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
- case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
- case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
- std::string path(mSysPath + "/device/vendor");
- std::string tmp;
- if (!ReadFileToString(path, &tmp)) {
- PLOG(WARNING) << "Failed to read vendor from " << path;
- return -errno;
- }
- tmp = android::base::Trim(tmp);
- mLabel = tmp;
- break;
- }
- case kMajorBlockMmc: {
- std::string path(mSysPath + "/device/manfid");
- std::string tmp;
- if (!ReadFileToString(path, &tmp)) {
- PLOG(WARNING) << "Failed to read manufacturer from " << path;
- return -errno;
- }
- tmp = android::base::Trim(tmp);
- int64_t manfid;
- if (!android::base::ParseInt(tmp, &manfid)) {
- PLOG(WARNING) << "Failed to parse manufacturer " << tmp;
- return -EINVAL;
- }
- // Our goal here is to give the user a meaningful label, ideally
- // matching whatever is silk-screened on the card. To reduce
- // user confusion, this list doesn't contain white-label manfid.
- switch (manfid) {
- case 0x000003: mLabel = "SanDisk"; break;
- case 0x00001b: mLabel = "Samsung"; break;
- case 0x000028: mLabel = "Lexar"; break;
- case 0x000074: mLabel = "Transcend"; break;
- }
- break;
- }
- default: {
- if (isVirtioBlkDevice(majorId)) {
- LOG(DEBUG) << "Recognized experimental block major ID " << majorId
- << " as virtio-blk (emulator's virtual SD card device)";
+ case kMajorBlockLoop: {
mLabel = "Virtual";
break;
}
- LOG(WARNING) << "Unsupported block major type " << majorId;
- return -ENOTSUP;
- }
+ // clang-format off
+ case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC:
+ case kMajorBlockScsiD: case kMajorBlockScsiE: case kMajorBlockScsiF:
+ case kMajorBlockScsiG: case kMajorBlockScsiH: case kMajorBlockScsiI:
+ case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
+ case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO:
+ case kMajorBlockScsiP: {
+ // clang-format on
+ std::string path(mSysPath + "/device/vendor");
+ std::string tmp;
+ if (!ReadFileToString(path, &tmp)) {
+ PLOG(WARNING) << "Failed to read vendor from " << path;
+ return -errno;
+ }
+ tmp = android::base::Trim(tmp);
+ mLabel = tmp;
+ break;
+ }
+ case kMajorBlockMmc: {
+ std::string path(mSysPath + "/device/manfid");
+ std::string tmp;
+ if (!ReadFileToString(path, &tmp)) {
+ PLOG(WARNING) << "Failed to read manufacturer from " << path;
+ return -errno;
+ }
+ tmp = android::base::Trim(tmp);
+ int64_t manfid;
+ if (!android::base::ParseInt(tmp, &manfid)) {
+ PLOG(WARNING) << "Failed to parse manufacturer " << tmp;
+ return -EINVAL;
+ }
+ // Our goal here is to give the user a meaningful label, ideally
+ // matching whatever is silk-screened on the card. To reduce
+ // user confusion, this list doesn't contain white-label manfid.
+ switch (manfid) {
+ // clang-format off
+ case 0x000003: mLabel = "SanDisk"; break;
+ case 0x00001b: mLabel = "Samsung"; break;
+ case 0x000028: mLabel = "Lexar"; break;
+ case 0x000074: mLabel = "Transcend"; break;
+ // clang-format on
+ }
+ break;
+ }
+ default: {
+ if (isVirtioBlkDevice(majorId)) {
+ LOG(DEBUG) << "Recognized experimental block major ID " << majorId
+ << " as virtio-blk (emulator's virtual SD card device)";
+ mLabel = "Virtual";
+ break;
+ }
+ if (isNvmeBlkDevice(majorId, mSysPath)) {
+ std::string path(mSysPath + "/device/model");
+ std::string tmp;
+ if (!ReadFileToString(path, &tmp)) {
+ PLOG(WARNING) << "Failed to read vendor from " << path;
+ return -errno;
+ }
+ mLabel = tmp;
+ break;
+ }
+ LOG(WARNING) << "Unsupported block major type " << majorId;
+ return -ENOTSUP;
+ }
}
auto listener = VolumeManager::Instance()->getListener();
- if (listener) listener->onDiskMetadataChanged(getId(),
- mSize, mLabel, mSysPath);
+ if (listener) listener->onDiskMetadataChanged(getId(), mSize, mLabel, mSysPath);
return OK;
}
@@ -320,7 +341,7 @@
cmd.push_back(mDevPath);
std::vector<std::string> output;
- status_t res = ForkExecvp(cmd, output);
+ status_t res = ForkExecvp(cmd, &output);
if (res != OK) {
LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
@@ -545,38 +566,49 @@
// Figure out maximum partition devices supported
unsigned int majorId = major(mDevice);
switch (majorId) {
- case kMajorBlockLoop: {
- std::string tmp;
- if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) {
- LOG(ERROR) << "Failed to read max minors";
- return -errno;
+ case kMajorBlockLoop: {
+ std::string tmp;
+ if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) {
+ LOG(ERROR) << "Failed to read max minors";
+ return -errno;
+ }
+ return std::stoi(tmp);
}
- return std::stoi(tmp);
- }
- case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
- case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
- case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
- case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
- // Per Documentation/devices.txt this is static
- return 15;
- }
- case kMajorBlockMmc: {
- // Per Documentation/devices.txt this is dynamic
- std::string tmp;
- if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp) &&
- !ReadFileToString(kSysfsMmcMaxMinorsDeprecated, &tmp)) {
- LOG(ERROR) << "Failed to read max minors";
- return -errno;
- }
- return std::stoi(tmp);
- }
- default: {
- if (isVirtioBlkDevice(majorId)) {
- // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is
- // 2^4 - 1 = 15
+ // clang-format off
+ case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC:
+ case kMajorBlockScsiD: case kMajorBlockScsiE: case kMajorBlockScsiF:
+ case kMajorBlockScsiG: case kMajorBlockScsiH: case kMajorBlockScsiI:
+ case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
+ case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO:
+ case kMajorBlockScsiP: {
+ // clang-format on
+ // Per Documentation/devices.txt this is static
return 15;
}
- }
+ case kMajorBlockMmc: {
+ // Per Documentation/devices.txt this is dynamic
+ std::string tmp;
+ if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp) &&
+ !ReadFileToString(kSysfsMmcMaxMinorsDeprecated, &tmp)) {
+ LOG(ERROR) << "Failed to read max minors";
+ return -errno;
+ }
+ return std::stoi(tmp);
+ }
+ default: {
+ if (isVirtioBlkDevice(majorId)) {
+ // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is
+ // 2^4 - 1 = 15
+ return 15;
+ }
+ if (isNvmeBlkDevice(majorId, mSysPath)) {
+ // despite kernel nvme driver supports up to 1M minors,
+ // #define NVME_MINORS (1U << MINORBITS)
+ // sgdisk can not support more than 127 partitions, due to
+ // #define MAX_MBR_PARTS 128
+ return 127;
+ }
+ }
}
LOG(ERROR) << "Unsupported block major type " << majorId;
diff --git a/model/Disk.h b/model/Disk.h
index 63acf6a..889e906 100644
--- a/model/Disk.h
+++ b/model/Disk.h
@@ -36,7 +36,7 @@
* how to repartition itself.
*/
class Disk {
-public:
+ public:
Disk(const std::string& eventPath, dev_t device, const std::string& nickname, int flags);
virtual ~Disk();
@@ -54,18 +54,18 @@
kEmmc = 1 << 4,
};
- const std::string& getId() { return mId; }
- const std::string& getEventPath() { return mEventPath; }
- const std::string& getSysPath() { return mSysPath; }
- const std::string& getDevPath() { return mDevPath; }
- dev_t getDevice() { return mDevice; }
- uint64_t getSize() { return mSize; }
- const std::string& getLabel() { return mLabel; }
- int getFlags() { return mFlags; }
+ const std::string& getId() const { return mId; }
+ const std::string& getEventPath() const { return mEventPath; }
+ const std::string& getSysPath() const { return mSysPath; }
+ const std::string& getDevPath() const { return mDevPath; }
+ dev_t getDevice() const { return mDevice; }
+ uint64_t getSize() const { return mSize; }
+ const std::string& getLabel() const { return mLabel; }
+ int getFlags() const { return mFlags; }
std::shared_ptr<VolumeBase> findVolume(const std::string& id);
- void listVolumes(VolumeBase::Type type, std::list<std::string>& list);
+ void listVolumes(VolumeBase::Type type, std::list<std::string>& list) const;
status_t create();
status_t destroy();
@@ -79,7 +79,7 @@
status_t partitionPrivate();
status_t partitionMixed(int8_t ratio);
-private:
+ private:
/* ID that uniquely references this disk */
std::string mId;
/* Original event path */
diff --git a/model/EmulatedVolume.cpp b/model/EmulatedVolume.cpp
index 31c3924..73bf6d1 100644
--- a/model/EmulatedVolume.cpp
+++ b/model/EmulatedVolume.cpp
@@ -16,9 +16,10 @@
#include "EmulatedVolume.h"
#include "Utils.h"
+#include "VolumeManager.h"
-#include <android-base/stringprintf.h>
#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
#include <cutils/fs.h>
#include <private/android_filesystem_config.h>
#include <utils/Timers.h>
@@ -27,8 +28,8 @@
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/stat.h>
-#include <sys/types.h>
#include <sys/sysmacros.h>
+#include <sys/types.h>
#include <sys/wait.h>
using android::base::StringPrintf;
@@ -38,22 +39,21 @@
static const char* kFusePath = "/system/bin/sdcard";
-EmulatedVolume::EmulatedVolume(const std::string& rawPath) :
- VolumeBase(Type::kEmulated), mFusePid(0) {
+EmulatedVolume::EmulatedVolume(const std::string& rawPath)
+ : VolumeBase(Type::kEmulated), mFusePid(0) {
setId("emulated");
mRawPath = rawPath;
mLabel = "emulated";
}
-EmulatedVolume::EmulatedVolume(const std::string& rawPath, dev_t device,
- const std::string& fsUuid) : VolumeBase(Type::kEmulated), mFusePid(0) {
+EmulatedVolume::EmulatedVolume(const std::string& rawPath, dev_t device, const std::string& fsUuid)
+ : VolumeBase(Type::kEmulated), mFusePid(0) {
setId(StringPrintf("emulated:%u,%u", major(device), minor(device)));
mRawPath = rawPath;
mLabel = fsUuid;
}
-EmulatedVolume::~EmulatedVolume() {
-}
+EmulatedVolume::~EmulatedVolume() {}
status_t EmulatedVolume::doMount() {
// We could have migrated storage to an adopted private volume, so always
@@ -66,20 +66,24 @@
mFuseDefault = StringPrintf("/mnt/runtime/default/%s", label.c_str());
mFuseRead = StringPrintf("/mnt/runtime/read/%s", label.c_str());
mFuseWrite = StringPrintf("/mnt/runtime/write/%s", label.c_str());
+ mFuseFull = StringPrintf("/mnt/runtime/full/%s", label.c_str());
setInternalPath(mRawPath);
setPath(StringPrintf("/storage/%s", label.c_str()));
+ setLabel(label);
if (fs_prepare_dir(mFuseDefault.c_str(), 0700, AID_ROOT, AID_ROOT) ||
- fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
- fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT)) {
+ fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
+ fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT) ||
+ fs_prepare_dir(mFuseFull.c_str(), 0700, AID_ROOT, AID_ROOT)) {
PLOG(ERROR) << getId() << " failed to create mount points";
return -errno;
}
- dev_t before = GetDevice(mFuseWrite);
+ dev_t before = GetDevice(mFuseFull);
if (!(mFusePid = fork())) {
+ // clang-format off
if (execl(kFusePath, kFusePath,
"-u", "1023", // AID_MEDIA_RW
"-g", "1023", // AID_MEDIA_RW
@@ -87,9 +91,11 @@
"-w",
"-G",
"-i",
+ "-o",
mRawPath.c_str(),
label.c_str(),
NULL)) {
+ // clang-format on
PLOG(ERROR) << "Failed to exec";
}
@@ -103,9 +109,9 @@
}
nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
- while (before == GetDevice(mFuseWrite)) {
- LOG(VERBOSE) << "Waiting for FUSE to spin up...";
- usleep(50000); // 50ms
+ while (before == GetDevice(mFuseFull)) {
+ LOG(DEBUG) << "Waiting for FUSE to spin up...";
+ usleep(50000); // 50ms
nsecs_t now = systemTime(SYSTEM_TIME_BOOTTIME);
if (nanoseconds_to_milliseconds(now - start) > 5000) {
@@ -114,8 +120,8 @@
}
}
/* sdcardfs will have exited already. FUSE will still be running */
- if (TEMP_FAILURE_RETRY(waitpid(mFusePid, nullptr, WNOHANG)) == mFusePid)
- mFusePid = 0;
+ TEMP_FAILURE_RETRY(waitpid(mFusePid, nullptr, 0));
+ mFusePid = 0;
return OK;
}
@@ -129,20 +135,17 @@
ForceUnmount(mFuseDefault);
ForceUnmount(mFuseRead);
ForceUnmount(mFuseWrite);
-
- if (mFusePid > 0) {
- kill(mFusePid, SIGTERM);
- TEMP_FAILURE_RETRY(waitpid(mFusePid, nullptr, 0));
- mFusePid = 0;
- }
+ ForceUnmount(mFuseFull);
rmdir(mFuseDefault.c_str());
rmdir(mFuseRead.c_str());
rmdir(mFuseWrite.c_str());
+ rmdir(mFuseFull.c_str());
mFuseDefault.clear();
mFuseRead.clear();
mFuseWrite.clear();
+ mFuseFull.clear();
return OK;
}
diff --git a/model/EmulatedVolume.h b/model/EmulatedVolume.h
index 9b0c049..fddfe4e 100644
--- a/model/EmulatedVolume.h
+++ b/model/EmulatedVolume.h
@@ -36,22 +36,23 @@
* store data local to their app.
*/
class EmulatedVolume : public VolumeBase {
-public:
+ public:
explicit EmulatedVolume(const std::string& rawPath);
EmulatedVolume(const std::string& rawPath, dev_t device, const std::string& fsUuid);
virtual ~EmulatedVolume();
-protected:
+ protected:
status_t doMount() override;
status_t doUnmount() override;
-private:
+ private:
std::string mRawPath;
std::string mLabel;
std::string mFuseDefault;
std::string mFuseRead;
std::string mFuseWrite;
+ std::string mFuseFull;
/* PID of FUSE wrapper */
pid_t mFusePid;
diff --git a/model/ObbVolume.cpp b/model/ObbVolume.cpp
index 709c7a3..21479c4 100644
--- a/model/ObbVolume.cpp
+++ b/model/ObbVolume.cpp
@@ -14,16 +14,15 @@
* limitations under the License.
*/
-#include "fs/Vfat.h"
+#include "ObbVolume.h"
#include "Devmapper.h"
#include "Loop.h"
-#include "ObbVolume.h"
#include "Utils.h"
#include "VoldUtil.h"
+#include "fs/Vfat.h"
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
-#include <android-base/unique_fd.h>
#include <cutils/fs.h>
#include <private/android_filesystem_config.h>
@@ -31,26 +30,25 @@
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/stat.h>
-#include <sys/types.h>
#include <sys/sysmacros.h>
+#include <sys/types.h>
#include <sys/wait.h>
using android::base::StringPrintf;
-using android::base::unique_fd;
namespace android {
namespace vold {
ObbVolume::ObbVolume(int id, const std::string& sourcePath, const std::string& sourceKey,
- gid_t ownerGid) : VolumeBase(Type::kObb) {
+ gid_t ownerGid)
+ : VolumeBase(Type::kObb) {
setId(StringPrintf("obb:%d", id));
mSourcePath = sourcePath;
mSourceKey = sourceKey;
mOwnerGid = ownerGid;
}
-ObbVolume::~ObbVolume() {
-}
+ObbVolume::~ObbVolume() {}
status_t ObbVolume::doCreate() {
if (Loop::create(mSourcePath, mLoopPath)) {
@@ -59,24 +57,15 @@
}
if (!mSourceKey.empty()) {
- unsigned long nr_sec = 0;
- {
- unique_fd loop_fd(open(mLoopPath.c_str(), O_RDWR | O_CLOEXEC));
- if (loop_fd.get() == -1) {
- PLOG(ERROR) << getId() << " failed to open loop";
- return -1;
- }
-
- get_blkdev_size(loop_fd.get(), &nr_sec);
- if (nr_sec == 0) {
- PLOG(ERROR) << getId() << " failed to get loop size";
- return -1;
- }
+ uint64_t nr_sec = 0;
+ if (GetBlockDev512Sectors(mLoopPath, &nr_sec) != OK) {
+ PLOG(ERROR) << getId() << " failed to get loop size";
+ return -1;
}
char tmp[PATH_MAX];
- if (Devmapper::create(getId().c_str(), mLoopPath.c_str(), mSourceKey.c_str(), nr_sec,
- tmp, PATH_MAX)) {
+ if (Devmapper::create(getId().c_str(), mLoopPath.c_str(), mSourceKey.c_str(), nr_sec, tmp,
+ PATH_MAX)) {
PLOG(ERROR) << getId() << " failed to create dm";
return -1;
}
@@ -108,8 +97,10 @@
PLOG(ERROR) << getId() << " failed to create mount point";
return -1;
}
- if (android::vold::vfat::Mount(mMountPath, path,
- true, false, true, 0, mOwnerGid, 0227, false)) {
+ // clang-format off
+ if (android::vold::vfat::Mount(mMountPath, path, true, false, true,
+ 0, mOwnerGid, 0227, false)) {
+ // clang-format on
PLOG(ERROR) << getId() << " failed to mount";
return -1;
}
diff --git a/model/ObbVolume.h b/model/ObbVolume.h
index 5ec0cde..8f7ee94 100644
--- a/model/ObbVolume.h
+++ b/model/ObbVolume.h
@@ -28,18 +28,17 @@
* OBB container.
*/
class ObbVolume : public VolumeBase {
-public:
- ObbVolume(int id, const std::string& sourcePath, const std::string& sourceKey,
- gid_t ownerGid);
+ public:
+ ObbVolume(int id, const std::string& sourcePath, const std::string& sourceKey, gid_t ownerGid);
virtual ~ObbVolume();
-protected:
+ protected:
status_t doCreate() override;
status_t doDestroy() override;
status_t doMount() override;
status_t doUnmount() override;
-private:
+ private:
std::string mSourcePath;
std::string mSourceKey;
gid_t mOwnerGid;
diff --git a/model/PrivateVolume.cpp b/model/PrivateVolume.cpp
index cf21577..de2a09f 100644
--- a/model/PrivateVolume.cpp
+++ b/model/PrivateVolume.cpp
@@ -14,27 +14,27 @@
* limitations under the License.
*/
-#include "fs/Ext4.h"
-#include "fs/F2fs.h"
#include "PrivateVolume.h"
#include "EmulatedVolume.h"
#include "Utils.h"
#include "VolumeManager.h"
#include "cryptfs.h"
+#include "fs/Ext4.h"
+#include "fs/F2fs.h"
-#include <android-base/stringprintf.h>
#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
#include <cutils/fs.h>
#include <private/android_filesystem_config.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mount.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/sysmacros.h>
-#include <sys/wait.h>
#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <sys/types.h>
+#include <sys/wait.h>
using android::base::StringPrintf;
@@ -43,14 +43,13 @@
static const unsigned int kMajorBlockMmc = 179;
-PrivateVolume::PrivateVolume(dev_t device, const std::string& keyRaw) :
- VolumeBase(Type::kPrivate), mRawDevice(device), mKeyRaw(keyRaw) {
+PrivateVolume::PrivateVolume(dev_t device, const std::string& keyRaw)
+ : VolumeBase(Type::kPrivate), mRawDevice(device), mKeyRaw(keyRaw) {
setId(StringPrintf("private:%u,%u", major(device), minor(device)));
mRawDevPath = StringPrintf("/dev/block/vold/%s", getId().c_str());
}
-PrivateVolume::~PrivateVolume() {
-}
+PrivateVolume::~PrivateVolume() {}
status_t PrivateVolume::readMetadata() {
status_t res = ReadMetadata(mDmDevPath, &mFsType, &mFsUuid, &mFsLabel);
@@ -66,9 +65,9 @@
return -EIO;
}
if (mKeyRaw.size() != cryptfs_get_keysize()) {
- PLOG(ERROR) << getId() << " Raw keysize " << mKeyRaw.size() <<
- " does not match crypt keysize " << cryptfs_get_keysize();
- return -EIO;
+ PLOG(ERROR) << getId() << " Raw keysize " << mKeyRaw.size()
+ << " does not match crypt keysize " << cryptfs_get_keysize();
+ return -EIO;
}
// Recover from stale vold by tearing down any old mappings
@@ -76,10 +75,9 @@
// TODO: figure out better SELinux labels for private volumes
- unsigned char* key = (unsigned char*) mKeyRaw.data();
+ unsigned char* key = (unsigned char*)mKeyRaw.data();
char crypto_blkdev[MAXPATHLEN];
- int res = cryptfs_setup_ext_volume(getId().c_str(), mRawDevPath.c_str(),
- key, crypto_blkdev);
+ int res = cryptfs_setup_ext_volume(getId().c_str(), mRawDevPath.c_str(), key, crypto_blkdev);
mDmDevPath = crypto_blkdev;
if (res != 0) {
PLOG(ERROR) << getId() << " failed to setup cryptfs";
@@ -147,12 +145,12 @@
// Verify that common directories are ready to roll
if (PrepareDir(mPath + "/app", 0771, AID_SYSTEM, AID_SYSTEM) ||
- PrepareDir(mPath + "/user", 0711, AID_SYSTEM, AID_SYSTEM) ||
- PrepareDir(mPath + "/user_de", 0711, AID_SYSTEM, AID_SYSTEM) ||
- PrepareDir(mPath + "/media", 0770, AID_MEDIA_RW, AID_MEDIA_RW) ||
- PrepareDir(mPath + "/media/0", 0770, AID_MEDIA_RW, AID_MEDIA_RW) ||
- PrepareDir(mPath + "/local", 0751, AID_ROOT, AID_ROOT) ||
- PrepareDir(mPath + "/local/tmp", 0771, AID_SHELL, AID_SHELL)) {
+ PrepareDir(mPath + "/user", 0711, AID_SYSTEM, AID_SYSTEM) ||
+ PrepareDir(mPath + "/user_de", 0711, AID_SYSTEM, AID_SYSTEM) ||
+ PrepareDir(mPath + "/media", 0770, AID_MEDIA_RW, AID_MEDIA_RW) ||
+ PrepareDir(mPath + "/media/0", 0770, AID_MEDIA_RW, AID_MEDIA_RW) ||
+ PrepareDir(mPath + "/local", 0751, AID_ROOT, AID_ROOT) ||
+ PrepareDir(mPath + "/local/tmp", 0771, AID_SHELL, AID_SHELL)) {
PLOG(ERROR) << getId() << " failed to prepare";
return -EIO;
}
@@ -160,8 +158,7 @@
// Create a new emulated volume stacked above us, it will automatically
// be destroyed during unmount
std::string mediaPath(mPath + "/media");
- auto vol = std::shared_ptr<VolumeBase>(
- new EmulatedVolume(mediaPath, mRawDevice, mFsUuid));
+ auto vol = std::shared_ptr<VolumeBase>(new EmulatedVolume(mediaPath, mRawDevice, mFsUuid));
addVolume(vol);
vol->create();
diff --git a/model/PrivateVolume.h b/model/PrivateVolume.h
index 9a61f8d..cb8e75d 100644
--- a/model/PrivateVolume.h
+++ b/model/PrivateVolume.h
@@ -36,14 +36,14 @@
* keys are tightly tied to this device.
*/
class PrivateVolume : public VolumeBase {
-public:
+ public:
PrivateVolume(dev_t device, const std::string& keyRaw);
virtual ~PrivateVolume();
- const std::string& getFsType() { return mFsType; };
- const std::string& getRawDevPath() { return mRawDevPath; };
- const std::string& getRawDmDevPath() { return mDmDevPath; };
+ const std::string& getFsType() const { return mFsType; };
+ const std::string& getRawDevPath() const { return mRawDevPath; };
+ const std::string& getRawDmDevPath() const { return mDmDevPath; };
-protected:
+ protected:
status_t doCreate() override;
status_t doDestroy() override;
status_t doMount() override;
@@ -52,7 +52,7 @@
status_t readMetadata();
-private:
+ private:
/* Kernel device of raw, encrypted partition */
dev_t mRawDevice;
/* Path to raw, encrypted block device */
diff --git a/model/PublicVolume.cpp b/model/PublicVolume.cpp
index fc7e96f..1eb6008 100644
--- a/model/PublicVolume.cpp
+++ b/model/PublicVolume.cpp
@@ -20,8 +20,9 @@
#include "fs/Exfat.h"
#include "fs/Vfat.h"
-#include <android-base/stringprintf.h>
#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
#include <cutils/fs.h>
#include <private/android_filesystem_config.h>
#include <utils/Timers.h>
@@ -30,10 +31,11 @@
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/stat.h>
-#include <sys/types.h>
#include <sys/sysmacros.h>
+#include <sys/types.h>
#include <sys/wait.h>
+using android::base::GetBoolProperty;
using android::base::StringPrintf;
namespace android {
@@ -43,14 +45,12 @@
static const char* kAsecPath = "/mnt/secure/asec";
-PublicVolume::PublicVolume(dev_t device) :
- VolumeBase(Type::kPublic), mDevice(device), mFusePid(0) {
+PublicVolume::PublicVolume(dev_t device) : VolumeBase(Type::kPublic), mDevice(device), mFusePid(0) {
setId(StringPrintf("public:%u,%u", major(device), minor(device)));
mDevPath = StringPrintf("/dev/block/vold/%s", getId().c_str());
}
-PublicVolume::~PublicVolume() {
-}
+PublicVolume::~PublicVolume() {}
status_t PublicVolume::readMetadata() {
status_t res = ReadMetadataUntrusted(mDevPath, &mFsType, &mFsUuid, &mFsLabel);
@@ -66,8 +66,7 @@
std::string securePath(mRawPath + "/.android_secure");
// Recover legacy secure path
- if (!access(legacyPath.c_str(), R_OK | X_OK)
- && access(securePath.c_str(), R_OK | X_OK)) {
+ if (!access(legacyPath.c_str(), R_OK | X_OK) && access(securePath.c_str(), R_OK | X_OK)) {
if (rename(legacyPath.c_str(), securePath.c_str())) {
PLOG(WARNING) << getId() << " failed to rename legacy ASEC dir";
}
@@ -122,6 +121,7 @@
mFuseDefault = StringPrintf("/mnt/runtime/default/%s", stableName.c_str());
mFuseRead = StringPrintf("/mnt/runtime/read/%s", stableName.c_str());
mFuseWrite = StringPrintf("/mnt/runtime/write/%s", stableName.c_str());
+ mFuseFull = StringPrintf("/mnt/runtime/full/%s", stableName.c_str());
setInternalPath(mRawPath);
if (getMountFlags() & MountFlags::kVisible) {
@@ -129,6 +129,7 @@
} else {
setPath(mRawPath);
}
+ setLabel(stableName);
if (fs_prepare_dir(mRawPath.c_str(), 0700, AID_ROOT, AID_ROOT)) {
PLOG(ERROR) << getId() << " failed to create mount points";
@@ -158,16 +159,18 @@
}
if (fs_prepare_dir(mFuseDefault.c_str(), 0700, AID_ROOT, AID_ROOT) ||
- fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
- fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT)) {
+ fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
+ fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT) ||
+ fs_prepare_dir(mFuseFull.c_str(), 0700, AID_ROOT, AID_ROOT)) {
PLOG(ERROR) << getId() << " failed to create FUSE mount points";
return -errno;
}
- dev_t before = GetDevice(mFuseWrite);
+ dev_t before = GetDevice(mFuseFull);
if (!(mFusePid = fork())) {
if (getMountFlags() & MountFlags::kPrimary) {
+ // clang-format off
if (execl(kFusePath, kFusePath,
"-u", "1023", // AID_MEDIA_RW
"-g", "1023", // AID_MEDIA_RW
@@ -176,9 +179,11 @@
mRawPath.c_str(),
stableName.c_str(),
NULL)) {
+ // clang-format on
PLOG(ERROR) << "Failed to exec";
}
} else {
+ // clang-format off
if (execl(kFusePath, kFusePath,
"-u", "1023", // AID_MEDIA_RW
"-g", "1023", // AID_MEDIA_RW
@@ -186,6 +191,7 @@
mRawPath.c_str(),
stableName.c_str(),
NULL)) {
+ // clang-format on
PLOG(ERROR) << "Failed to exec";
}
}
@@ -200,9 +206,9 @@
}
nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
- while (before == GetDevice(mFuseWrite)) {
- LOG(VERBOSE) << "Waiting for FUSE to spin up...";
- usleep(50000); // 50ms
+ while (before == GetDevice(mFuseFull)) {
+ LOG(DEBUG) << "Waiting for FUSE to spin up...";
+ usleep(50000); // 50ms
nsecs_t now = systemTime(SYSTEM_TIME_BOOTTIME);
if (nanoseconds_to_milliseconds(now - start) > 5000) {
@@ -211,8 +217,8 @@
}
}
/* sdcardfs will have exited already. FUSE will still be running */
- if (TEMP_FAILURE_RETRY(waitpid(mFusePid, nullptr, WNOHANG)) == mFusePid)
- mFusePid = 0;
+ TEMP_FAILURE_RETRY(waitpid(mFusePid, nullptr, 0));
+ mFusePid = 0;
return OK;
}
@@ -229,50 +235,72 @@
ForceUnmount(mFuseDefault);
ForceUnmount(mFuseRead);
ForceUnmount(mFuseWrite);
+ ForceUnmount(mFuseFull);
ForceUnmount(mRawPath);
- if (mFusePid > 0) {
- kill(mFusePid, SIGTERM);
- TEMP_FAILURE_RETRY(waitpid(mFusePid, nullptr, 0));
- mFusePid = 0;
- }
-
rmdir(mFuseDefault.c_str());
rmdir(mFuseRead.c_str());
rmdir(mFuseWrite.c_str());
+ rmdir(mFuseFull.c_str());
rmdir(mRawPath.c_str());
mFuseDefault.clear();
mFuseRead.clear();
mFuseWrite.clear();
+ mFuseFull.clear();
mRawPath.clear();
return OK;
}
status_t PublicVolume::doFormat(const std::string& fsType) {
- if ((fsType == "vfat" || fsType == "auto") && vfat::IsSupported()) {
- if (WipeBlockDevice(mDevPath) != OK) {
- LOG(WARNING) << getId() << " failed to wipe";
+ bool useVfat = vfat::IsSupported();
+ bool useExfat = exfat::IsSupported();
+ status_t res = OK;
+
+ // Resolve the target filesystem type
+ if (fsType == "auto" && useVfat && useExfat) {
+ uint64_t size = 0;
+
+ res = GetBlockDevSize(mDevPath, &size);
+ if (res != OK) {
+ LOG(ERROR) << "Couldn't get device size " << mDevPath;
+ return res;
}
- if (vfat::Format(mDevPath, 0)) {
- LOG(ERROR) << getId() << " failed to format";
- return -errno;
+
+ // If both vfat & exfat are supported use exfat for SDXC (>~32GiB) cards
+ if (size > 32896LL * 1024 * 1024) {
+ useVfat = false;
+ } else {
+ useExfat = false;
}
- } else if ((fsType == "exfat" || fsType == "auto") && exfat::IsSupported()) {
- if (WipeBlockDevice(mDevPath) != OK) {
- LOG(WARNING) << getId() << " failed to wipe";
- }
- if (exfat::Format(mDevPath)) {
- LOG(ERROR) << getId() << " failed to format";
- return -errno;
- }
- } else {
+ } else if (fsType == "vfat") {
+ useExfat = false;
+ } else if (fsType == "exfat") {
+ useVfat = false;
+ }
+
+ if (!useVfat && !useExfat) {
LOG(ERROR) << "Unsupported filesystem " << fsType;
return -EINVAL;
}
- return OK;
+ if (WipeBlockDevice(mDevPath) != OK) {
+ LOG(WARNING) << getId() << " failed to wipe";
+ }
+
+ if (useVfat) {
+ res = vfat::Format(mDevPath, 0);
+ } else if (useExfat) {
+ res = exfat::Format(mDevPath);
+ }
+
+ if (res != OK) {
+ LOG(ERROR) << getId() << " failed to format";
+ res = -errno;
+ }
+
+ return res;
}
} // namespace vold
diff --git a/model/PublicVolume.h b/model/PublicVolume.h
index 3aa7a73..2feccca 100644
--- a/model/PublicVolume.h
+++ b/model/PublicVolume.h
@@ -38,11 +38,11 @@
* away the Android directory for secondary users.
*/
class PublicVolume : public VolumeBase {
-public:
+ public:
explicit PublicVolume(dev_t device);
virtual ~PublicVolume();
-protected:
+ protected:
status_t doCreate() override;
status_t doDestroy() override;
status_t doMount() override;
@@ -52,7 +52,7 @@
status_t readMetadata();
status_t initAsecStage();
-private:
+ private:
/* Kernel device representing partition */
dev_t mDevice;
/* Block device path */
@@ -63,6 +63,7 @@
std::string mFuseDefault;
std::string mFuseRead;
std::string mFuseWrite;
+ std::string mFuseFull;
/* PID of FUSE wrapper */
pid_t mFusePid;
diff --git a/model/StubVolume.cpp b/model/StubVolume.cpp
new file mode 100644
index 0000000..edd0861
--- /dev/null
+++ b/model/StubVolume.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "StubVolume.h"
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+
+using android::base::StringPrintf;
+
+namespace android {
+namespace vold {
+
+StubVolume::StubVolume(int id, const std::string& sourcePath, const std::string& mountPath,
+ const std::string& fsType, const std::string& fsUuid,
+ const std::string& fsLabel)
+ : VolumeBase(Type::kStub),
+ mSourcePath(sourcePath),
+ mMountPath(mountPath),
+ mFsType(fsType),
+ mFsUuid(fsUuid),
+ mFsLabel(fsLabel) {
+ setId(StringPrintf("stub:%d", id));
+}
+
+StubVolume::~StubVolume() {}
+
+status_t StubVolume::doCreate() {
+ return OK;
+}
+
+status_t StubVolume::doDestroy() {
+ return OK;
+}
+
+status_t StubVolume::doMount() {
+ auto listener = getListener();
+ if (listener) listener->onVolumeMetadataChanged(getId(), mFsType, mFsUuid, mFsLabel);
+ setInternalPath(mSourcePath);
+ setPath(mMountPath);
+ return OK;
+}
+
+status_t StubVolume::doUnmount() {
+ return OK;
+}
+
+// TODO: return error instead.
+status_t StubVolume::doFormat(const std::string& fsType) {
+ return OK;
+}
+
+} // namespace vold
+} // namespace android
diff --git a/model/StubVolume.h b/model/StubVolume.h
new file mode 100644
index 0000000..538cae9
--- /dev/null
+++ b/model/StubVolume.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_VOLD_STUB_VOLUME_H
+#define ANDROID_VOLD_STUB_VOLUME_H
+
+#include "VolumeBase.h"
+
+namespace android {
+namespace vold {
+
+/*
+ * A vold representation of volumes managed from outside Android (e.g., ARC++).
+ *
+ * Used for the case when events such that mounting and unmounting are
+ * actually handled from outside vold, and vold only need to keep track on those
+ * vents instead of talking to kernel directly.
+ */
+class StubVolume : public VolumeBase {
+ public:
+ StubVolume(int id, const std::string& sourcePath, const std::string& mountPath,
+ const std::string& fsType, const std::string& fsUuid, const std::string& fsLabel);
+ virtual ~StubVolume();
+
+ protected:
+ status_t doCreate() override;
+ status_t doDestroy() override;
+ status_t doMount() override;
+ status_t doUnmount() override;
+ status_t doFormat(const std::string& fsType) override;
+
+ private:
+ const std::string mSourcePath;
+ const std::string mMountPath;
+ const std::string mFsType;
+ const std::string mFsUuid;
+ const std::string mFsLabel;
+
+ DISALLOW_COPY_AND_ASSIGN(StubVolume);
+};
+
+} // namespace vold
+} // namespace android
+
+#endif
diff --git a/model/VolumeBase.cpp b/model/VolumeBase.cpp
index 429f134..a9c7fa3 100644
--- a/model/VolumeBase.cpp
+++ b/model/VolumeBase.cpp
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-#include "Utils.h"
#include "VolumeBase.h"
+#include "Utils.h"
#include "VolumeManager.h"
-#include <android-base/stringprintf.h>
#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
#include <fcntl.h>
#include <stdlib.h>
@@ -32,10 +32,13 @@
namespace android {
namespace vold {
-VolumeBase::VolumeBase(Type type) :
- mType(type), mMountFlags(0), mMountUserId(-1), mCreated(false), mState(
- State::kUnmounted), mSilent(false) {
-}
+VolumeBase::VolumeBase(Type type)
+ : mType(type),
+ mMountFlags(0),
+ mMountUserId(USER_UNKNOWN),
+ mCreated(false),
+ mState(State::kUnmounted),
+ mSilent(false) {}
VolumeBase::~VolumeBase() {
CHECK(!mCreated);
@@ -45,7 +48,9 @@
mState = state;
auto listener = getListener();
- if (listener) listener->onVolumeStateChanged(getId(), static_cast<int32_t>(mState));
+ if (listener) {
+ listener->onVolumeStateChanged(getId(), static_cast<int32_t>(mState));
+ }
}
status_t VolumeBase::setDiskId(const std::string& diskId) {
@@ -131,12 +136,24 @@
mInternalPath = internalPath;
auto listener = getListener();
- if (listener) listener->onVolumeInternalPathChanged(getId(), mInternalPath);
+ if (listener) {
+ listener->onVolumeInternalPathChanged(getId(), mInternalPath);
+ }
return OK;
}
-android::sp<android::os::IVoldListener> VolumeBase::getListener() {
+status_t VolumeBase::setLabel(const std::string& label) {
+ if (mState != State::kChecking) {
+ LOG(WARNING) << getId() << " label change requires state checking";
+ return -EBUSY;
+ }
+
+ mLabel = label;
+ return OK;
+}
+
+android::sp<android::os::IVoldListener> VolumeBase::getListener() const {
if (mSilent) {
return nullptr;
} else {
@@ -168,8 +185,9 @@
status_t res = doCreate();
auto listener = getListener();
- if (listener) listener->onVolumeCreated(getId(),
- static_cast<int32_t>(mType), mDiskId, mPartGuid);
+ if (listener) {
+ listener->onVolumeCreated(getId(), static_cast<int32_t>(mType), mDiskId, mPartGuid);
+ }
setState(State::kUnmounted);
return res;
@@ -189,9 +207,10 @@
setState(State::kRemoved);
}
-
auto listener = getListener();
- if (listener) listener->onVolumeDestroyed(getId());
+ if (listener) {
+ listener->onVolumeDestroyed(getId());
+ }
status_t res = doDestroy();
mCreated = false;
@@ -211,10 +230,9 @@
setState(State::kChecking);
status_t res = doMount();
if (res == OK) {
- setState(State::kMounted);
- } else {
- setState(State::kUnmountable);
+ res = VolumeManager::Instance()->onVolumeMounted(this);
}
+ setState(res == OK ? State::kMounted : State::kUnmountable);
return res;
}
@@ -228,14 +246,16 @@
setState(State::kEjecting);
for (const auto& vol : mVolumes) {
if (vol->destroy()) {
- LOG(WARNING) << getId() << " failed to destroy " << vol->getId()
- << " stacked above";
+ LOG(WARNING) << getId() << " failed to destroy " << vol->getId() << " stacked above";
}
}
mVolumes.clear();
- status_t res = doUnmount();
- setState(State::kUnmounted);
+ status_t res = VolumeManager::Instance()->onVolumeUnmounted(this);
+ if (res == OK) {
+ res = doUnmount();
+ setState(State::kUnmounted);
+ }
return res;
}
@@ -259,5 +279,10 @@
return -ENOTSUP;
}
+std::ostream& VolumeBase::operator<<(std::ostream& stream) const {
+ return stream << " VolumeBase{id=" << mId << ",label=" << mLabel
+ << ",mountFlags=" << mMountFlags << ",mountUserId=" << mMountUserId << "}";
+}
+
} // namespace vold
} // namespace android
diff --git a/model/VolumeBase.h b/model/VolumeBase.h
index 4aa8b02..e6c47f0 100644
--- a/model/VolumeBase.h
+++ b/model/VolumeBase.h
@@ -17,8 +17,8 @@
#ifndef ANDROID_VOLD_VOLUME_BASE_H
#define ANDROID_VOLD_VOLUME_BASE_H
-#include "android/os/IVoldListener.h"
#include "Utils.h"
+#include "android/os/IVoldListener.h"
#include <cutils/multiuser.h>
#include <utils/Errors.h>
@@ -27,6 +27,8 @@
#include <list>
#include <string>
+static constexpr userid_t USER_UNKNOWN = ((userid_t)-1);
+
namespace android {
namespace vold {
@@ -45,7 +47,7 @@
* volumes and removes any bind mounts before finally unmounting itself.
*/
class VolumeBase {
-public:
+ public:
virtual ~VolumeBase();
enum class Type {
@@ -54,6 +56,7 @@
kEmulated,
kAsec,
kObb,
+ kStub,
};
enum MountFlags {
@@ -75,15 +78,16 @@
kBadRemoval,
};
- const std::string& getId() { return mId; }
- const std::string& getDiskId() { return mDiskId; }
- const std::string& getPartGuid() { return mPartGuid; }
- Type getType() { return mType; }
- int getMountFlags() { return mMountFlags; }
- userid_t getMountUserId() { return mMountUserId; }
- State getState() { return mState; }
- const std::string& getPath() { return mPath; }
- const std::string& getInternalPath() { return mInternalPath; }
+ const std::string& getId() const { return mId; }
+ const std::string& getDiskId() const { return mDiskId; }
+ const std::string& getPartGuid() const { return mPartGuid; }
+ Type getType() const { return mType; }
+ int getMountFlags() const { return mMountFlags; }
+ userid_t getMountUserId() const { return mMountUserId; }
+ State getState() const { return mState; }
+ const std::string& getPath() const { return mPath; }
+ const std::string& getInternalPath() const { return mInternalPath; }
+ const std::string& getLabel() const { return mLabel; }
status_t setDiskId(const std::string& diskId);
status_t setPartGuid(const std::string& partGuid);
@@ -96,13 +100,17 @@
std::shared_ptr<VolumeBase> findVolume(const std::string& id);
+ bool isEmulated() { return mType == Type::kEmulated; }
+
status_t create();
status_t destroy();
status_t mount();
status_t unmount();
status_t format(const std::string& fsType);
-protected:
+ std::ostream& operator<<(std::ostream& stream) const;
+
+ protected:
explicit VolumeBase(Type type);
virtual status_t doCreate();
@@ -114,10 +122,11 @@
status_t setId(const std::string& id);
status_t setPath(const std::string& path);
status_t setInternalPath(const std::string& internalPath);
+ status_t setLabel(const std::string& label);
- android::sp<android::os::IVoldListener> getListener();
+ android::sp<android::os::IVoldListener> getListener() const;
-private:
+ private:
/* ID that uniquely references volume while alive */
std::string mId;
/* ID that uniquely references parent disk while alive */
@@ -140,6 +149,12 @@
std::string mInternalPath;
/* Flag indicating that volume should emit no events */
bool mSilent;
+ /**
+ * Label used for representing the package sandboxes on external storage volumes.
+ * For emulated volume, this would be "emulated" and for public volumes, UUID if available,
+ * otherwise some other unique id.
+ */
+ std::string mLabel;
/* Volumes stacked on top of this volume */
std::list<std::shared_ptr<VolumeBase>> mVolumes;
diff --git a/secdiscard.cpp b/secdiscard.cpp
index f9532ea..0ff05d6 100644
--- a/secdiscard.cpp
+++ b/secdiscard.cpp
@@ -18,15 +18,15 @@
#include <string>
#include <vector>
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/fiemap.h>
+#include <linux/fs.h>
+#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
-#include <errno.h>
-#include <sys/types.h>
#include <sys/stat.h>
-#include <fcntl.h>
-#include <linux/fs.h>
-#include <linux/fiemap.h>
-#include <mntent.h>
+#include <sys/types.h>
#include <android-base/logging.h>
#include <android-base/unique_fd.h>
@@ -42,22 +42,48 @@
constexpr uint32_t max_extents = 32;
-bool read_command_line(int argc, const char * const argv[], Options &options);
-void usage(const char *progname);
-bool secdiscard_path(const std::string &path);
-bool check_fiemap(const struct fiemap &fiemap, const std::string &path);
+bool read_command_line(int argc, const char* const argv[], Options& options);
+void usage(const char* progname);
+bool secdiscard_path(const std::string& path);
+bool check_fiemap(const struct fiemap& fiemap, const std::string& path);
bool overwrite_with_zeros(int fd, off64_t start, off64_t length);
-}
+} // namespace
-int main(int argc, const char * const argv[]) {
- android::base::InitLogging(const_cast<char **>(argv));
+int main(int argc, const char* const argv[]) {
+ android::base::InitLogging(const_cast<char**>(argv));
Options options;
if (!read_command_line(argc, argv, options)) {
usage(argv[0]);
return -1;
}
- for (auto const &target: options.targets) {
+
+ for (auto const& target : options.targets) {
+// F2FS-specific ioctl
+// It requires the below kernel commit merged in v4.16-rc1.
+// 1ad71a27124c ("f2fs: add an ioctl to disable GC for specific file")
+// In android-4.4,
+// 56ee1e817908 ("f2fs: updates on v4.16-rc1")
+// In android-4.9,
+// 2f17e34672a8 ("f2fs: updates on v4.16-rc1")
+// In android-4.14,
+// ce767d9a55bc ("f2fs: updates on v4.16-rc1")
+#ifndef F2FS_IOC_SET_PIN_FILE
+#ifndef F2FS_IOCTL_MAGIC
+#define F2FS_IOCTL_MAGIC 0xf5
+#endif
+#define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32)
+#define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32)
+#endif
+ android::base::unique_fd fd(
+ TEMP_FAILURE_RETRY(open(target.c_str(), O_WRONLY | O_CLOEXEC, 0)));
+ if (fd == -1) {
+ LOG(ERROR) << "Secure discard open failed for: " << target;
+ return 0;
+ }
+ __u32 set = 1;
+ ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set);
+
LOG(DEBUG) << "Securely discarding '" << target << "' unlink=" << options.unlink;
if (!secdiscard_path(target)) {
LOG(ERROR) << "Secure discard failed for: " << target;
@@ -67,36 +93,37 @@
PLOG(ERROR) << "Unable to unlink: " << target;
}
}
- LOG(DEBUG) << "Discarded: " << target;
+ set = 0;
+ ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set);
}
return 0;
}
namespace {
-bool read_command_line(int argc, const char * const argv[], Options &options) {
+bool read_command_line(int argc, const char* const argv[], Options& options) {
for (int i = 1; i < argc; i++) {
if (!strcmp("--no-unlink", argv[i])) {
options.unlink = false;
} else if (!strcmp("--", argv[i])) {
- for (int j = i+1; j < argc; j++) {
- if (argv[j][0] != '/') return false; // Must be absolute path
+ for (int j = i + 1; j < argc; j++) {
+ if (argv[j][0] != '/') return false; // Must be absolute path
options.targets.emplace_back(argv[j]);
}
return options.targets.size() > 0;
} else {
- return false; // Unknown option
+ return false; // Unknown option
}
}
- return false; // "--" not found
+ return false; // "--" not found
}
-void usage(const char *progname) {
+void usage(const char* progname) {
fprintf(stderr, "Usage: %s [--no-unlink] -- <absolute path> ...\n", progname);
}
// BLKSECDISCARD all content in "path", if it's small enough.
-bool secdiscard_path(const std::string &path) {
+bool secdiscard_path(const std::string& path) {
auto fiemap = android::vold::PathFiemap(path, max_extents);
if (!fiemap || !check_fiemap(*fiemap, path)) {
return false;
@@ -105,8 +132,8 @@
if (block_device.empty()) {
return false;
}
- android::base::unique_fd fs_fd(TEMP_FAILURE_RETRY(open(
- block_device.c_str(), O_RDWR | O_LARGEFILE | O_CLOEXEC, 0)));
+ android::base::unique_fd fs_fd(
+ TEMP_FAILURE_RETRY(open(block_device.c_str(), O_RDWR | O_LARGEFILE | O_CLOEXEC, 0)));
if (fs_fd == -1) {
PLOG(ERROR) << "Failed to open device " << block_device;
return false;
@@ -116,19 +143,18 @@
range[0] = fiemap->fm_extents[i].fe_physical;
range[1] = fiemap->fm_extents[i].fe_length;
if (ioctl(fs_fd.get(), BLKSECDISCARD, range) == -1) {
- PLOG(ERROR) << "Unable to BLKSECDISCARD " << path;
+ // Use zero overwrite as a fallback for BLKSECDISCARD
if (!overwrite_with_zeros(fs_fd.get(), range[0], range[1])) return false;
- LOG(DEBUG) << "Used zero overwrite";
}
}
return true;
}
// Ensure that the FIEMAP covers the file and is OK to discard
-bool check_fiemap(const struct fiemap &fiemap, const std::string &path) {
+bool check_fiemap(const struct fiemap& fiemap, const std::string& path) {
auto mapped = fiemap.fm_mapped_extents;
if (!(fiemap.fm_extents[mapped - 1].fe_flags & FIEMAP_EXTENT_LAST)) {
- LOG(ERROR) << "Extent " << mapped -1 << " was not the last in " << path;
+ LOG(ERROR) << "Extent " << mapped - 1 << " was not the last in " << path;
return false;
}
for (uint32_t i = 0; i < mapped; i++) {
@@ -160,4 +186,4 @@
return true;
}
-}
+} // namespace
diff --git a/secontext.cpp b/secontext.cpp
deleted file mode 100644
index 0529a30..0000000
--- a/secontext.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <Utils.h>
-#include "secontext.h"
-
-security_context_t secontextFsck()
-{
- return android::vold::sFsckContext;
-}
diff --git a/secontext.h b/secontext.h
deleted file mode 100644
index f5339c8..0000000
--- a/secontext.h
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef _SECONTEXT_H_
-#define _SECONTEXT_H_
-
-#include <selinux/selinux.h>
-
-security_context_t secontextFsck();
-
-#endif
diff --git a/sehandle.h b/sehandle.h
index f59d7eb..8921db5 100644
--- a/sehandle.h
+++ b/sehandle.h
@@ -19,6 +19,6 @@
#include <selinux/android.h>
-extern struct selabel_handle *sehandle;
+extern struct selabel_handle* sehandle;
#endif
diff --git a/tests/CryptfsScryptHidlizationEquivalence_test.cpp b/tests/CryptfsScryptHidlizationEquivalence_test.cpp
index 2905af2..72170e3 100644
--- a/tests/CryptfsScryptHidlizationEquivalence_test.cpp
+++ b/tests/CryptfsScryptHidlizationEquivalence_test.cpp
@@ -18,13 +18,13 @@
#define LOG_TAG "scrypt_test"
#include <log/log.h>
+#include <gtest/gtest.h>
#include <hardware/keymaster0.h>
#include <hardware/keymaster1.h>
#include <cstring>
-#include <gtest/gtest.h>
-#include "../cryptfs.h"
#include "../Keymaster.h"
+#include "../cryptfs.h"
#ifdef CONFIG_HW_DISK_ENCRYPTION
#include "cryptfs_hw.h"
@@ -50,9 +50,8 @@
#define RSA_EXPONENT 0x10001
#define KEYMASTER_CRYPTFS_RATE_LIMIT 1 // Maximum one try per second
-static int keymaster_init(keymaster0_device_t **keymaster0_dev,
- keymaster1_device_t **keymaster1_dev)
-{
+static int keymaster_init(keymaster0_device_t** keymaster0_dev,
+ keymaster1_device_t** keymaster1_dev) {
int rc;
const hw_module_t* mod;
@@ -76,8 +75,8 @@
}
if (rc) {
- ALOGE("could not open keymaster device in %s (%s)",
- KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
+ ALOGE("could not open keymaster device in %s (%s)", KEYSTORE_HARDWARE_MODULE_ID,
+ strerror(-rc));
goto err;
}
@@ -90,10 +89,9 @@
}
/* Should we use keymaster? */
-static int keymaster_check_compatibility_old()
-{
- keymaster0_device_t *keymaster0_dev = 0;
- keymaster1_device_t *keymaster1_dev = 0;
+static int keymaster_check_compatibility_old() {
+ keymaster0_device_t* keymaster0_dev = 0;
+ keymaster1_device_t* keymaster1_dev = 0;
int rc = 0;
if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
@@ -114,8 +112,7 @@
// TODO(swillden): Check to see if there's any reason to require v0.3. I think v0.1 and v0.2
// should work.
- if (keymaster0_dev->common.module->module_api_version
- < KEYMASTER_MODULE_API_VERSION_0_3) {
+ if (keymaster0_dev->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_3) {
rc = 0;
goto out;
}
@@ -136,11 +133,10 @@
}
/* Create a new keymaster key and store it in this footer */
-static int keymaster_create_key_old(struct crypt_mnt_ftr *ftr)
-{
+static int keymaster_create_key_old(struct crypt_mnt_ftr* ftr) {
uint8_t* key = 0;
- keymaster0_device_t *keymaster0_dev = 0;
- keymaster1_device_t *keymaster1_dev = 0;
+ keymaster0_device_t* keymaster0_dev = 0;
+ keymaster1_device_t* keymaster1_dev = 0;
if (ftr->keymaster_blob_size) {
SLOGI("Already have key");
@@ -177,11 +173,10 @@
/* Rate-limit key usage attempts, to rate-limit brute force */
keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
};
- keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
+ keymaster_key_param_set_t param_set = {params, sizeof(params) / sizeof(*params)};
keymaster_key_blob_t key_blob;
- keymaster_error_t error = keymaster1_dev->generate_key(keymaster1_dev, ¶m_set,
- &key_blob,
- NULL /* characteristics */);
+ keymaster_error_t error = keymaster1_dev->generate_key(
+ keymaster1_dev, ¶m_set, &key_blob, NULL /* characteristics */);
if (error != KM_ERROR_OK) {
SLOGE("Failed to generate keymaster1 key, error %d", error);
rc = -1;
@@ -190,15 +185,13 @@
key = (uint8_t*)key_blob.key_material;
key_size = key_blob.key_material_size;
- }
- else if (keymaster0_dev) {
+ } else if (keymaster0_dev) {
keymaster_rsa_keygen_params_t params;
memset(¶ms, '\0', sizeof(params));
params.public_exponent = RSA_EXPONENT;
params.modulus_size = RSA_KEY_SIZE;
- if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, ¶ms,
- &key, &key_size)) {
+ if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, ¶ms, &key, &key_size)) {
SLOGE("Failed to generate keypair");
rc = -1;
goto out;
@@ -219,24 +212,19 @@
ftr->keymaster_blob_size = key_size;
out:
- if (keymaster0_dev)
- keymaster0_close(keymaster0_dev);
- if (keymaster1_dev)
- keymaster1_close(keymaster1_dev);
+ if (keymaster0_dev) keymaster0_close(keymaster0_dev);
+ if (keymaster1_dev) keymaster1_close(keymaster1_dev);
free(key);
return rc;
}
/* This signs the given object using the keymaster key. */
-static int keymaster_sign_object_old(struct crypt_mnt_ftr *ftr,
- const unsigned char *object,
- const size_t object_size,
- unsigned char **signature,
- size_t *signature_size)
-{
+static int keymaster_sign_object_old(struct crypt_mnt_ftr* ftr, const unsigned char* object,
+ const size_t object_size, unsigned char** signature,
+ size_t* signature_size) {
int rc = 0;
- keymaster0_device_t *keymaster0_dev = 0;
- keymaster1_device_t *keymaster1_dev = 0;
+ keymaster0_device_t* keymaster0_dev = 0;
+ keymaster1_device_t* keymaster1_dev = 0;
unsigned char to_sign[RSA_KEY_SIZE_BYTES];
size_t to_sign_size = sizeof(to_sign);
@@ -284,32 +272,25 @@
params.digest_type = DIGEST_NONE;
params.padding_type = PADDING_NONE;
- rc = keymaster0_dev->sign_data(keymaster0_dev,
- ¶ms,
- ftr->keymaster_blob,
- ftr->keymaster_blob_size,
- to_sign,
- to_sign_size,
- signature,
- signature_size);
+ rc = keymaster0_dev->sign_data(keymaster0_dev, ¶ms, ftr->keymaster_blob,
+ ftr->keymaster_blob_size, to_sign, to_sign_size, signature,
+ signature_size);
goto out;
} else if (keymaster1_dev) {
- keymaster_key_blob_t key = { ftr->keymaster_blob, ftr->keymaster_blob_size };
+ keymaster_key_blob_t key = {ftr->keymaster_blob, ftr->keymaster_blob_size};
keymaster_key_param_t params[] = {
keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
};
- keymaster_key_param_set_t param_set = { params, sizeof(params)/sizeof(*params) };
+ keymaster_key_param_set_t param_set = {params, sizeof(params) / sizeof(*params)};
keymaster_operation_handle_t op_handle;
- keymaster_error_t error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
- ¶m_set, NULL /* out_params */,
- &op_handle);
+ keymaster_error_t error = keymaster1_dev->begin(
+ keymaster1_dev, KM_PURPOSE_SIGN, &key, ¶m_set, NULL /* out_params */, &op_handle);
if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
// Key usage has been rate-limited. Wait a bit and try again.
sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
- error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key,
- ¶m_set, NULL /* out_params */,
- &op_handle);
+ error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key, ¶m_set,
+ NULL /* out_params */, &op_handle);
}
if (error != KM_ERROR_OK) {
SLOGE("Error starting keymaster signature transaction: %d", error);
@@ -317,11 +298,10 @@
goto out;
}
- keymaster_blob_t input = { to_sign, to_sign_size };
+ keymaster_blob_t input = {to_sign, to_sign_size};
size_t input_consumed;
- error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */,
- &input, &input_consumed, NULL /* out_params */,
- NULL /* output */);
+ error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */, &input,
+ &input_consumed, NULL /* out_params */, NULL /* output */);
if (error != KM_ERROR_OK) {
SLOGE("Error sending data to keymaster signature transaction: %d", error);
rc = -1;
@@ -337,8 +317,7 @@
keymaster_blob_t tmp_sig;
error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
- NULL /* verify signature */, NULL /* out_params */,
- &tmp_sig);
+ NULL /* verify signature */, NULL /* out_params */, &tmp_sig);
if (error != KM_ERROR_OK) {
SLOGE("Error finishing keymaster signature transaction: %d", error);
rc = -1;
@@ -353,19 +332,15 @@
goto out;
}
- out:
- if (keymaster1_dev)
- keymaster1_close(keymaster1_dev);
- if (keymaster0_dev)
- keymaster0_close(keymaster0_dev);
+out:
+ if (keymaster1_dev) keymaster1_close(keymaster1_dev);
+ if (keymaster0_dev) keymaster0_close(keymaster0_dev);
- return rc;
+ return rc;
}
-
/* Should we use keymaster? */
-static int keymaster_check_compatibility_new()
-{
+static int keymaster_check_compatibility_new() {
return keymaster_compatibility_cryptfs_scrypt();
}
@@ -394,12 +369,9 @@
#endif
/* This signs the given object using the keymaster key. */
-static int keymaster_sign_object_new(struct crypt_mnt_ftr *ftr,
- const unsigned char *object,
- const size_t object_size,
- unsigned char **signature,
- size_t *signature_size)
-{
+static int keymaster_sign_object_new(struct crypt_mnt_ftr* ftr, const unsigned char* object,
+ const size_t object_size, unsigned char** signature,
+ size_t* signature_size) {
unsigned char to_sign[RSA_KEY_SIZE_BYTES];
size_t to_sign_size = sizeof(to_sign);
memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
@@ -443,12 +415,10 @@
namespace android {
class CryptFsTest : public testing::Test {
-protected:
- virtual void SetUp() {
- }
+ protected:
+ virtual void SetUp() {}
- virtual void TearDown() {
- }
+ virtual void TearDown() {}
};
TEST_F(CryptFsTest, ScryptHidlizationEquivalenceTest) {
@@ -458,8 +428,8 @@
ASSERT_EQ(0, keymaster_create_key_old(&ftr));
- uint8_t *sig1 = nullptr;
- uint8_t *sig2 = nullptr;
+ uint8_t* sig1 = nullptr;
+ uint8_t* sig2 = nullptr;
size_t sig_size1 = 123456789;
size_t sig_size2 = 123456789;
uint8_t object[] = "the object";
@@ -477,4 +447,4 @@
free(sig2);
}
-}
+} // namespace android
diff --git a/tests/Utils_test.cpp b/tests/Utils_test.cpp
index ab9809e..d18dc67 100644
--- a/tests/Utils_test.cpp
+++ b/tests/Utils_test.cpp
@@ -21,13 +21,13 @@
namespace android {
namespace vold {
-class UtilsTest : public testing::Test {
-};
+class UtilsTest : public testing::Test {};
TEST_F(UtilsTest, FindValueTest) {
std::string tmp;
ASSERT_FALSE(FindValue("", "KEY", &tmp));
+ ASSERT_FALSE(FindValue("NOTMATCH=\"VALUE\"", "KEY", &tmp));
ASSERT_FALSE(FindValue("BADKEY=\"VALUE\"", "KEY", &tmp));
ASSERT_TRUE(FindValue("KEY=\"VALUE\"", "KEY", &tmp));
@@ -38,7 +38,10 @@
ASSERT_TRUE(FindValue("BADKEY=\"VALUE\" KEY=\"BAZ\"", "KEY", &tmp));
ASSERT_EQ("BAZ", tmp);
+
+ ASSERT_TRUE(FindValue("BADKEY=\"VALUE\" NOTKEY=\"OTHER\" KEY=\"QUUX\"", "KEY", &tmp));
+ ASSERT_EQ("QUUX", tmp);
}
-}
-}
+} // namespace vold
+} // namespace android
diff --git a/tests/cryptfs_test.cpp b/tests/cryptfs_test.cpp
index 6875c0f..2093768 100644
--- a/tests/cryptfs_test.cpp
+++ b/tests/cryptfs_test.cpp
@@ -21,12 +21,10 @@
namespace android {
class CryptfsTest : public testing::Test {
-protected:
- virtual void SetUp() {
- }
+ protected:
+ virtual void SetUp() {}
- virtual void TearDown() {
- }
+ virtual void TearDown() {}
};
TEST_F(CryptfsTest, MatchMultiEntryTest) {
@@ -51,4 +49,4 @@
ASSERT_EQ(0, match_multi_entry("foo_2", "bar", 0));
}
-}
+} // namespace android
diff --git a/vdc.cpp b/vdc.cpp
index 3c449ae..76eca3e 100644
--- a/vdc.cpp
+++ b/vdc.cpp
@@ -14,15 +14,14 @@
* limitations under the License.
*/
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <signal.h>
#include <errno.h>
#include <fcntl.h>
-#include <stdlib.h>
#include <poll.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
@@ -32,13 +31,14 @@
#include "android/os/IVold.h"
#include <android-base/logging.h>
+#include <android-base/parseint.h>
#include <android-base/stringprintf.h>
#include <binder/IServiceManager.h>
#include <binder/Status.h>
#include <private/android_filesystem_config.h>
-static void usage(char *progname);
+static void usage(char* progname);
static android::sp<android::IBinder> getServiceAggressive() {
android::sp<android::IBinder> res;
@@ -50,7 +50,7 @@
LOG(VERBOSE) << "Waited " << (i * 10) << "ms for vold";
break;
}
- usleep(10000); // 10ms
+ usleep(10000); // 10ms
}
return res;
}
@@ -105,6 +105,46 @@
checkStatus(vold->mountFstab(args[2]));
} else if (args[0] == "cryptfs" && args[1] == "encryptFstab" && args.size() == 3) {
checkStatus(vold->encryptFstab(args[2]));
+ } else if (args[0] == "checkpoint" && args[1] == "supportsCheckpoint" && args.size() == 2) {
+ bool supported = false;
+ checkStatus(vold->supportsCheckpoint(&supported));
+ return supported ? 1 : 0;
+ } else if (args[0] == "checkpoint" && args[1] == "supportsBlockCheckpoint" && args.size() == 2) {
+ bool supported = false;
+ checkStatus(vold->supportsBlockCheckpoint(&supported));
+ return supported ? 1 : 0;
+ } else if (args[0] == "checkpoint" && args[1] == "supportsFileCheckpoint" && args.size() == 2) {
+ bool supported = false;
+ checkStatus(vold->supportsFileCheckpoint(&supported));
+ return supported ? 1 : 0;
+ } else if (args[0] == "checkpoint" && args[1] == "startCheckpoint" && args.size() == 3) {
+ int retry;
+ if (!android::base::ParseInt(args[2], &retry)) exit(EINVAL);
+ checkStatus(vold->startCheckpoint(retry));
+ } else if (args[0] == "checkpoint" && args[1] == "needsCheckpoint" && args.size() == 2) {
+ bool enabled = false;
+ checkStatus(vold->needsCheckpoint(&enabled));
+ return enabled ? 1 : 0;
+ } else if (args[0] == "checkpoint" && args[1] == "needsRollback" && args.size() == 2) {
+ bool enabled = false;
+ checkStatus(vold->needsRollback(&enabled));
+ return enabled ? 1 : 0;
+ } else if (args[0] == "checkpoint" && args[1] == "commitChanges" && args.size() == 2) {
+ checkStatus(vold->commitChanges());
+ } else if (args[0] == "checkpoint" && args[1] == "prepareCheckpoint" && args.size() == 2) {
+ checkStatus(vold->prepareCheckpoint());
+ } else if (args[0] == "checkpoint" && args[1] == "restoreCheckpoint" && args.size() == 3) {
+ checkStatus(vold->restoreCheckpoint(args[2]));
+ } else if (args[0] == "checkpoint" && args[1] == "restoreCheckpointPart" && args.size() == 4) {
+ int count;
+ if (!android::base::ParseInt(args[3], &count)) exit(EINVAL);
+ checkStatus(vold->restoreCheckpointPart(args[2], count));
+ } else if (args[0] == "checkpoint" && args[1] == "markBootAttempt" && args.size() == 2) {
+ checkStatus(vold->markBootAttempt());
+ } else if (args[0] == "checkpoint" && args[1] == "abortChanges" && args.size() == 4) {
+ int retry;
+ if (!android::base::ParseInt(args[2], &retry)) exit(EINVAL);
+ checkStatus(vold->abortChanges(args[2], retry != 0));
} else {
LOG(ERROR) << "Raw commands are no longer supported";
exit(EINVAL);
@@ -112,6 +152,6 @@
return 0;
}
-static void usage(char *progname) {
+static void usage(char* progname) {
LOG(INFO) << "Usage: " << progname << " [--wait] <system> <subcommand> [args...]";
}
diff --git a/vold.rc b/vold.rc
index 7d14453..93d8786 100644
--- a/vold.rc
+++ b/vold.rc
@@ -5,4 +5,4 @@
ioprio be 2
writepid /dev/cpuset/foreground/tasks
shutdown critical
- group reserved_disk
+ group root reserved_disk
diff --git a/vold_prepare_subdirs.cpp b/vold_prepare_subdirs.cpp
index 1b466e9..1dd5e85 100644
--- a/vold_prepare_subdirs.cpp
+++ b/vold_prepare_subdirs.cpp
@@ -63,7 +63,8 @@
secontext.reset(tmp_secontext);
}
LOG(DEBUG) << "Setting up mode " << std::oct << mode << std::dec << " uid " << uid << " gid "
- << gid << " context " << secontext.get() << " on path: " << path;
+ << gid << " context " << (secontext ? secontext.get() : "null")
+ << " on path: " << path;
if (secontext) {
if (setfscreatecon(secontext.get()) != 0) {
PLOG(ERROR) << "Unable to read setfscreatecon for: " << path;
@@ -127,16 +128,31 @@
auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/vold")) return false;
if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/storaged")) return false;
+ if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/rollback")) return false;
auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, vendor_de_path + "/fpdata")) {
return false;
}
+ auto facedata_path = vendor_de_path + "/facedata";
+ if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, facedata_path)) {
+ return false;
+ }
}
if (flags & android::os::IVold::STORAGE_FLAG_CE) {
auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/vold")) return false;
if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/storaged")) return false;
+ if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/rollback")) return false;
+
+ auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
+ if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, system_ce_path + "/backup")) {
+ return false;
+ }
+ if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM,
+ system_ce_path + "/backup_stage")) {
+ return false;
+ }
}
}
return true;