blob: dc6fae98ddbc99c740b29d54067f9a038576b903 [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Ricky Waie96b34f2020-05-07 16:01:33 +010022#include <limits.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080023#include <mntent.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/ioctl.h>
28#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080029#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070030#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070031#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070032#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080033#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070034#include <array>
San Mehata19b2502010-01-06 10:33:53 -080035
San Mehata2677e42009-12-13 10:40:18 -080036#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070037
Jiyong Park8d21c922019-01-04 13:35:25 +090038#include <ApexProperties.sysprop.h>
Paul Lawrence24b7d2d2023-08-11 10:27:24 -070039#include <android-base/file.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080040#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070041#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060042#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080043#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070044#include <android-base/strings.h>
Narayan Kamath02efdf52019-11-27 10:53:51 +000045#include <async_safe/log.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070046
Jeff Sharkey71ebe152013-09-17 17:24:38 -070047#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060048#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070049
Robert Craigb9e3ba52014-02-04 10:53:00 -050050#include <selinux/android.h>
51
San Mehatfd7f5872009-10-12 11:32:47 -070052#include <sysutils/NetlinkEvent.h>
53
Kenny Root344ca102012-04-03 17:23:01 -070054#include <private/android_filesystem_config.h>
55
Eric Biggersa701c452018-10-23 13:06:55 -070056#include <fscrypt/fscrypt.h>
Paul Lawrence24b7d2d2023-08-11 10:27:24 -070057#include <libdm/dm.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070058
Risanac02a482018-10-31 21:59:47 -060059#include "AppFuseUtil.h"
Eric Biggersa701c452018-10-23 13:06:55 -070060#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080061#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070062#include "NetlinkManager.h"
63#include "Process.h"
64#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070065#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070066#include "VoldUtil.h"
67#include "VolumeManager.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070068#include "fs/Ext4.h"
69#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070070#include "model/EmulatedVolume.h"
71#include "model/ObbVolume.h"
Zima438b242019-09-25 14:37:38 +010072#include "model/PrivateVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090073#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080074
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000075using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070076using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070077using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070078using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070079using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060080using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080081using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000082using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080083using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080084using android::vold::DeleteDirContentsAndDir;
Ricky Wai07e64a42020-02-11 14:31:24 +000085using android::vold::EnsureDirExists;
Martijn Coenen73e30102022-07-12 08:11:02 +000086using android::vold::GetFuseMountPathForUser;
Martijn Coenen62a4b272020-01-31 15:23:09 +010087using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070088using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070089using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010090using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010091using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010092using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080093using android::vold::Symlink;
94using android::vold::Unlink;
95using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080096using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010097using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070098
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060099static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
100
101static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
102
Sudheer Shanka53947a32018-08-01 10:24:13 -0700103static const std::string kEmptyString("");
104
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600105/* 512MiB is large enough for testing purposes */
106static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700107
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700108static const unsigned int kMajorBlockMmc = 179;
109
Ricky Wai07e64a42020-02-11 14:31:24 +0000110using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
111
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700112VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700113
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700114VolumeManager* VolumeManager::Instance() {
115 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700116 return sInstance;
117}
118
119VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800120 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600121 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900122 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700123 // For security reasons, assume that a secure keyguard is
124 // showing until we hear otherwise
125 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700126}
127
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700128VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800129
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600130int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600131 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700132 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600133 if (access(kPathVirtualDisk, F_OK) != 0) {
134 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
135 }
136
137 if (mVirtualDisk == nullptr) {
138 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
139 LOG(ERROR) << "Failed to create virtual disk";
140 return -1;
141 }
142
143 struct stat buf;
144 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
145 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
146 return -1;
147 }
148
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700149 auto disk = new android::vold::Disk(
150 "virtual", buf.st_rdev, "virtual",
151 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600152 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700153 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600154 }
155 } else {
156 if (mVirtualDisk != nullptr) {
157 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700158 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600159
160 Loop::destroyByDevice(mVirtualDiskPath.c_str());
161 mVirtualDisk = nullptr;
162 }
163
164 if (access(kPathVirtualDisk, F_OK) == 0) {
165 unlink(kPathVirtualDisk);
166 }
167 }
168 return 0;
169}
170
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700171int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800172 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700173 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800174}
175
San Mehatf1b736b2009-10-10 17:22:08 -0700176int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600177 ATRACE_NAME("VolumeManager::start");
178
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700179 // Always start from a clean slate by unmounting everything in
180 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700181 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700182
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600183 Loop::destroyAll();
184
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700185 // Assume that we always have an emulated volume on internal
186 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100187 CHECK(mInternalEmulatedVolumes.empty());
188
189 auto vol = std::shared_ptr<android::vold::VolumeBase>(
190 new android::vold::EmulatedVolume("/data/media", 0));
191 vol->setMountUserId(0);
192 vol->create();
193 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600195 // Consider creating a virtual disk
196 updateVirtualDisk();
197
San Mehatf1b736b2009-10-10 17:22:08 -0700198 return 0;
199}
200
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700201void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700202 std::lock_guard<std::mutex> lock(mLock);
203
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700204 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700205 LOG(DEBUG) << "----------------";
206 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700207 evt->dump();
208 }
San Mehatf1b736b2009-10-10 17:22:08 -0700209
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700210 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
211 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700212
213 if (devType != "disk") return;
214
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600215 int major = std::stoi(evt->findParam("MAJOR"));
216 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700217 dev_t device = makedev(major, minor);
218
219 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700220 case NetlinkEvent::Action::kAdd: {
221 for (const auto& source : mDiskSources) {
222 if (source->matches(eventPath)) {
223 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700224 // specific to virtual platforms; see Utils.cpp for details)
225 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700226 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700227 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700228 flags |= android::vold::Disk::Flags::kSd;
229 } else {
230 flags |= android::vold::Disk::Flags::kUsb;
231 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700232
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700233 auto disk =
234 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
235 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
236 break;
237 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700239 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700240 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700241 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100242 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700243 handleDiskChanged(device);
244 break;
245 }
246 case NetlinkEvent::Action::kRemove: {
247 handleDiskRemoved(device);
248 break;
249 }
250 default: {
251 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
252 break;
253 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700254 }
255}
256
Jeff Sharkey401b2602017-12-14 22:15:20 -0700257void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
258 // For security reasons, if secure keyguard is showing, wait
259 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100260 // Additionally, wait until user 0 is actually started, since we need
261 // the user to be up before we can mount a FUSE daemon to handle the disk.
262 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700263 if (mSecureKeyguardShowing) {
264 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700265 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700266 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100267 } else if (!userZeroStarted) {
268 LOG(INFO) << "Found disk at " << disk->getEventPath()
269 << " but delaying scan due to user zero not having started";
270 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700271 } else {
272 disk->create();
273 mDisks.push_back(disk);
274 }
275}
276
277void VolumeManager::handleDiskChanged(dev_t device) {
278 for (const auto& disk : mDisks) {
279 if (disk->getDevice() == device) {
280 disk->readMetadata();
281 disk->readPartitions();
282 }
283 }
284
285 // For security reasons, we ignore all pending disks, since
286 // we'll scan them once the device is unlocked
287}
288
289void VolumeManager::handleDiskRemoved(dev_t device) {
290 auto i = mDisks.begin();
291 while (i != mDisks.end()) {
292 if ((*i)->getDevice() == device) {
293 (*i)->destroy();
294 i = mDisks.erase(i);
295 } else {
296 ++i;
297 }
298 }
299 auto j = mPendingDisks.begin();
300 while (j != mPendingDisks.end()) {
301 if ((*j)->getDevice() == device) {
302 j = mPendingDisks.erase(j);
303 } else {
304 ++j;
305 }
306 }
307}
308
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700309void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800310 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700311 mDiskSources.push_back(diskSource);
312}
313
314std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
315 for (auto disk : mDisks) {
316 if (disk->getId() == id) {
317 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700318 }
319 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700320 return nullptr;
321}
San Mehatf1b736b2009-10-10 17:22:08 -0700322
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700323std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100324 for (const auto& vol : mInternalEmulatedVolumes) {
325 if (vol->getId() == id) {
326 return vol;
327 }
San Mehatf1b736b2009-10-10 17:22:08 -0700328 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700329 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700330 auto vol = disk->findVolume(id);
331 if (vol != nullptr) {
332 return vol;
333 }
334 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600335 for (const auto& vol : mObbVolumes) {
336 if (vol->getId() == id) {
337 return vol;
338 }
339 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700340 return nullptr;
341}
342
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800343void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
344 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700345 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700346 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700347 disk->listVolumes(type, list);
348 }
349}
350
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600351int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700352 std::string normalizedGuid;
353 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
354 LOG(WARNING) << "Invalid GUID " << partGuid;
355 return -1;
356 }
357
Paul Crowleyc6433a22017-10-24 14:54:43 -0700358 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700359 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
360 if (unlink(keyPath.c_str()) != 0) {
361 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700362 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700363 }
Eric Biggersa6957c02022-06-15 18:52:18 +0000364 if (IsFbeEnabled()) {
Eric Biggersa701c452018-10-23 13:06:55 -0700365 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700366 success = false;
367 }
368 }
369 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700370}
371
Zima438b242019-09-25 14:37:38 +0100372void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
373 // Destroy and remove all unstacked EmulatedVolumes for the user
374 auto i = mInternalEmulatedVolumes.begin();
375 while (i != mInternalEmulatedVolumes.end()) {
376 auto vol = *i;
377 if (vol->getMountUserId() == userId) {
378 vol->destroy();
379 i = mInternalEmulatedVolumes.erase(i);
380 } else {
381 i++;
382 }
383 }
384
385 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
386 std::list<std::string> private_vols;
387 listVolumes(VolumeBase::Type::kPrivate, private_vols);
388 for (const std::string& id : private_vols) {
389 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
390 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
391 if (pvol->getState() == VolumeBase::State::kMounted) {
392 for (const auto& vol : pvol->getVolumes()) {
393 if (vol->getMountUserId() == userId) {
394 vols_to_remove.push_back(vol);
395 }
396 }
397 for (const auto& vol : vols_to_remove) {
398 vol->destroy();
399 pvol->removeVolume(vol);
400 }
401 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
402 }
403}
404
405void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
406 // Create unstacked EmulatedVolumes for the user
407 auto vol = std::shared_ptr<android::vold::VolumeBase>(
408 new android::vold::EmulatedVolume("/data/media", userId));
409 vol->setMountUserId(userId);
410 mInternalEmulatedVolumes.push_back(vol);
411 vol->create();
412
413 // Create stacked EmulatedVolumes for the user on each PrivateVolume
414 std::list<std::string> private_vols;
415 listVolumes(VolumeBase::Type::kPrivate, private_vols);
416 for (const std::string& id : private_vols) {
417 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
418 if (pvol->getState() == VolumeBase::State::kMounted) {
419 auto evol =
420 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
421 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
422 userId));
423 evol->setMountUserId(userId);
424 pvol->addVolume(evol);
425 evol->create();
426 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
427 }
428}
429
Martijn Coenen73e30102022-07-12 08:11:02 +0000430userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
431 if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
432 return USER_UNKNOWN;
433 }
434 return mSharedStorageUser.at(userId);
435}
436
437int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
438 userid_t sharesStorageWithUserId) {
Zima438b242019-09-25 14:37:38 +0100439 LOG(INFO) << "onUserAdded: " << userId;
440
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700441 mAddedUsers[userId] = userSerialNumber;
Martijn Coenen73e30102022-07-12 08:11:02 +0000442 if (sharesStorageWithUserId != USER_UNKNOWN) {
443 mSharedStorageUser[userId] = sharesStorageWithUserId;
444 }
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700445 return 0;
446}
447
448int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100449 LOG(INFO) << "onUserRemoved: " << userId;
450
Zim2d45d9b2019-11-14 16:19:05 +0000451 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700452 mAddedUsers.erase(userId);
Martijn Coenen73e30102022-07-12 08:11:02 +0000453 mSharedStorageUser.erase(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700454 return 0;
455}
456
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700457int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100458 LOG(INFO) << "onUserStarted: " << userId;
459
Zim2d45d9b2019-11-14 16:19:05 +0000460 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
461 createEmulatedVolumesForUser(userId);
462 }
463
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700464 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100465
466 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700467 return 0;
468}
469
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700470int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700471 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100472
Zim2d45d9b2019-11-14 16:19:05 +0000473 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100474 destroyEmulatedVolumesForUser(userId);
475 }
476
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700477 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700478 return 0;
479}
480
Martijn Coenencf5916f2020-01-03 14:36:45 +0100481void VolumeManager::createPendingDisksIfNeeded() {
482 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
483 if (!mSecureKeyguardShowing && userZeroStarted) {
484 // Now that secure keyguard has been dismissed and user 0 has
485 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700486 for (const auto& disk : mPendingDisks) {
487 disk->create();
488 mDisks.push_back(disk);
489 }
490 mPendingDisks.clear();
491 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100492}
493
494int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
495 mSecureKeyguardShowing = isShowing;
496 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700497 return 0;
498}
499
Narayan Kamath02efdf52019-11-27 10:53:51 +0000500// This code is executed after a fork so it's very important that the set of
501// methods we call here is strictly limited.
502//
503// TODO: Get rid of this guesswork altogether and instead exec a process
504// immediately after fork to do our bindding for us.
505static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000506 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000507 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000508 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000509 strerror(errno));
510 return false;
511 }
512
513 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
514 // to also protect against future changes that may cause issues across a
515 // fork.
516 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
517 errno != ENOENT) {
518 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
519 strerror(errno));
520 return false;
521 }
522
523 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
524 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000525 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000526 return false;
527 }
528
529 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
530 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000531 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000532 strerror(errno));
533 return false;
534 }
535
536 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
537 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000538 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000539 return false;
540 }
541
542 return true;
543}
544
Ricky Wai07e64a42020-02-11 14:31:24 +0000545// Fork the process and remount storage
546bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
547 int32_t mountMode = *static_cast<int32_t*>(params);
548 std::string userSource;
549 std::string storageSource;
550 pid_t child;
551 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800552 switch (mountMode) {
553 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000554 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800555 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000556 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800557 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000558 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700559 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000560 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800561 break;
Zim981222f2019-09-09 10:24:44 +0100562 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000563 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800564 default:
565 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000566 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800567 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000568 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700569
Ricky Wai07e64a42020-02-11 14:31:24 +0000570 // Fork a child to mount user-specific symlink helper into place
571 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
572 if (!(child = fork())) {
573 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
574 _exit(0);
575 } else {
576 _exit(1);
577 }
578 }
579
580 if (child == -1) {
581 PLOG(ERROR) << "Failed to fork";
582 return false;
583 } else {
584 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
585 }
586 return true;
587}
588
589// Helper function to scan all processes in /proc and call the callback if:
590// 1). pid belongs to an app process
591// 2). If input uid is 0 or it matches the process uid
592// 3). If userId is not -1 or userId matches the process userId
593bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700594 DIR* dir;
595 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600596 std::string rootName;
597 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700598 int pidFd;
599 int nsFd;
600 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700601
Jiyong Park8d21c922019-01-04 13:35:25 +0900602 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
603
Jeff Sharkey66270a22015-06-24 11:49:24 -0700604 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000605 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
606 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700607 }
608
609 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600610 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000611 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700612 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000613 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700614 }
615
Ricky Wai07e64a42020-02-11 14:31:24 +0000616 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700617 // Poke through all running PIDs look for apps running as UID
618 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700619 pid_t pid;
620 if (de->d_type != DT_DIR) continue;
621 if (!android::base::ParseInt(de->d_name, &pid)) continue;
622
Jeff Sharkey66270a22015-06-24 11:49:24 -0700623 pidFd = -1;
624 nsFd = -1;
625
626 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
627 if (pidFd < 0) {
628 goto next;
629 }
630 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000631 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700632 goto next;
633 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000634 if (uid != 0 && sb.st_uid != uid) {
635 goto next;
636 }
637 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700638 goto next;
639 }
640
641 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600642 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000643 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
644 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700645 goto next;
646 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600647 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700648 goto next;
649 }
650
Jiyong Park8d21c922019-01-04 13:35:25 +0900651 if (apexUpdatable) {
652 std::string exeName;
653 // When ro.apex.bionic_updatable is set to true,
654 // some early native processes have mount namespaces that are different
655 // from that of the init. Therefore, above check can't filter them out.
656 // Since the propagation type of / is 'shared', unmounting /storage
657 // for the early native processes affects other processes including
658 // init. Filter out such processes by skipping if a process is a
659 // non-Java process whose UID is < AID_APP_START. (The UID condition
660 // is required to not filter out child processes spawned by apps.)
661 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900662 goto next;
663 }
664 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900665 goto next;
666 }
667 }
668
Jeff Sharkey66270a22015-06-24 11:49:24 -0700669 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700670 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
671 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700672 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000673 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
674 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700675 goto next;
676 }
677
Ricky Wai07e64a42020-02-11 14:31:24 +0000678 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
679 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700680 }
681
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700682 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700683 close(nsFd);
684 close(pidFd);
685 }
686 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000687 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
688 return true;
689}
690
Ricky Waia2ca11e2021-01-15 14:03:23 +0000691// In each app's namespace, unmount obb and data dirs
692static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
693 int uid, const char* targets[], int size) {
694 // This code is executed after a fork so it's very important that the set of
695 // methods we call here is strictly limited.
696 if (setns(nsFd, CLONE_NEWNS) != 0) {
697 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
698 return false;
699 }
700
701 // Unmount of Android/data/foo needs to be done before Android/data below.
702 bool result = true;
703 for (int i = 0; i < size; i++) {
704 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
705 errno != ENOENT) {
706 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
707 targets[i], strerror(errno));
708 result = false;
709 }
710 }
711
712 // Mount tmpfs on Android/data and Android/obb
713 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
714 errno != ENOENT) {
715 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
716 android_data_dir, strerror(errno));
717 result = false;
718 }
719 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
720 errno != ENOENT) {
721 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
722 android_obb_dir, strerror(errno));
723 result = false;
724 }
725 return result;
726}
727
Ricky Waie96b34f2020-05-07 16:01:33 +0100728// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
729// package dirs.
730static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
731 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000732 // This code is executed after a fork so it's very important that the set of
733 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000734 if (setns(nsFd, CLONE_NEWNS) != 0) {
735 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
736 return false;
737 }
738
Ricky Waie96b34f2020-05-07 16:01:33 +0100739 // Mount tmpfs on Android/data and Android/obb
740 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
741 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
742 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
743 android_data_dir, strerror(errno));
744 return false;
745 }
746 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
747 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
748 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
749 android_obb_dir, strerror(errno));
750 return false;
751 }
752
Ricky Wai6b122572020-02-28 16:30:47 +0000753 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100754 // Create package dir and bind mount it to the actual one.
755 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
756 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
757 targets[i], strerror(errno));
758 return false;
759 }
Ricky Wai6b122572020-02-28 16:30:47 +0000760 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
761 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
762 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000763 return false;
764 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000765 }
766 return true;
767}
768
Ricky Wai6b122572020-02-28 16:30:47 +0000769static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
770 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700771 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000772 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
773 userId, dirName.c_str(), packageName.c_str());
774 } else {
775 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
776 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000777 }
Ricky Wai6b122572020-02-28 16:30:47 +0000778}
779
780static std::string getStorageDirTarget(userid_t userId, std::string dirName,
781 std::string packageName) {
782 return StringPrintf("/storage/emulated/%d/%s/%s",
783 userId, dirName.c_str(), packageName.c_str());
784}
785
Ricky Waia2ca11e2021-01-15 14:03:23 +0000786// Fork the process and remount / unmount app data and obb dirs
787bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000788 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000789 userid_t userId = multiuser_get_user_id(uid);
790 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
791 android::base::unique_fd nsFd(
792 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
793 if (nsFd == -1) {
794 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
795 return false;
796 }
797 // Storing both Android/obb and Android/data paths.
798 int size = packageNames.size() * 2;
799
800 std::unique_ptr<std::string[]> sources(new std::string[size]);
801 std::unique_ptr<std::string[]> targets(new std::string[size]);
802 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
803 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
804 const char** sources_cstr = sources_uptr.get();
805 const char** targets_cstr = targets_uptr.get();
806
807 for (int i = 0; i < size; i += 2) {
808 std::string const& packageName = packageNames[i/2];
809 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
810 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
811 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
812 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
813
814 sources_cstr[i] = sources[i].c_str();
815 targets_cstr[i] = targets[i].c_str();
816 sources_cstr[i+1] = sources[i+1].c_str();
817 targets_cstr[i+1] = targets[i+1].c_str();
818 }
819
820 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000821 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000822 // This needs to be done before EnsureDirExists to ensure Android/ is created.
823 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000824 if (status != OK) {
825 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
826 return false;
827 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000828 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
829 if (status != OK) {
830 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
831 return false;
832 }
Ricky Wai6b122572020-02-28 16:30:47 +0000833 }
834
Ricky Waie96b34f2020-05-07 16:01:33 +0100835 char android_data_dir[PATH_MAX];
836 char android_obb_dir[PATH_MAX];
837 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
838 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
839
Ricky Wai6b122572020-02-28 16:30:47 +0000840 pid_t child;
841 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
842 // original vold process mount namespace.
843 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000844 if (doUnmount) {
845 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
846 targets_cstr, size)) {
847 _exit(0);
848 } else {
849 _exit(1);
850 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000851 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000852 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
853 sources_cstr, targets_cstr, size)) {
854 _exit(0);
855 } else {
856 _exit(1);
857 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000858 }
859 }
Ricky Wai6b122572020-02-28 16:30:47 +0000860
Ricky Wai07e64a42020-02-11 14:31:24 +0000861 if (child == -1) {
862 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000863 return false;
864 } else {
865 int status;
866 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
867 PLOG(ERROR) << "Failed to waitpid: " << child;
868 return false;
869 }
870 if (!WIFEXITED(status)) {
871 PLOG(ERROR) << "Process did not exit normally, status: " << status;
872 return false;
873 }
874 if (WEXITSTATUS(status)) {
875 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
876 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000877 }
878 }
Ricky Wai6b122572020-02-28 16:30:47 +0000879 return true;
880}
881
Ricky Waia2ca11e2021-01-15 14:03:23 +0000882int VolumeManager::handleAppStorageDirs(int uid, int pid,
883 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000884 // Only run the remount if fuse is mounted for that user.
885 userid_t userId = multiuser_get_user_id(uid);
886 bool fuseMounted = false;
887 for (auto& vol : mInternalEmulatedVolumes) {
888 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
889 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
890 if (emulatedVol) {
891 fuseMounted = emulatedVol->isFuseMounted();
892 }
893 break;
894 }
895 }
896 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000897 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000898 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700899 return 0;
900}
901
Martijn Coenen23c04452020-04-29 07:49:41 +0200902int VolumeManager::abortFuse() {
903 return android::vold::AbortFuseConnections();
904}
905
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700906int VolumeManager::reset() {
907 // Tear down all existing disks/volumes and start from a blank slate so
908 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100909 for (const auto& vol : mInternalEmulatedVolumes) {
910 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800911 }
Zima438b242019-09-25 14:37:38 +0100912 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100913
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900914 // Destroy and recreate all disks except that StubVolume disks are just
915 // destroyed and removed from both mDisks and mPendingDisks.
916 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
917 // their disk recreation on reset events should be handled from outside by
918 // calling createStubVolume() again.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700919 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700920 disk->destroy();
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900921 if (!disk->isStub()) {
922 disk->create();
923 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700924 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900925 const auto isStub = [](const auto& disk) { return disk->isStub(); };
926 mDisks.remove_if(isStub);
927 mPendingDisks.remove_if(isStub);
928
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600929 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700930 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800931 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +0000932 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +0100933
934 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
935 // with FUSE fds open.
936 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700937 return 0;
938}
939
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700940// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700941int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100942 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700943 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700944 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700945 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100946 for (const auto& vol : mInternalEmulatedVolumes) {
947 vol->destroy();
948 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700949 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700950 disk->destroy();
951 }
Zima438b242019-09-25 14:37:38 +0100952
953 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700954 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700955 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700956 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200957
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700958 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700959}
960
Jeff Sharkey9c484982015-03-31 10:35:33 -0700961int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700962 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600963 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700964
Jeff Sharkey9c484982015-03-31 10:35:33 -0700965 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100966 for (const auto& vol : mInternalEmulatedVolumes) {
967 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700968 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700969 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700970 disk->unmountAll();
971 }
972
973 // Worst case we might have some stale mounts lurking around, so
974 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800975 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700976 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600977 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700978 return -errno;
979 }
980
981 // Some volumes can be stacked on each other, so force unmount in
982 // reverse order to give us the best chance of success.
983 std::list<std::string> toUnmount;
984 mntent* mentry;
985 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600986 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700987 if ((StartsWith(test, "/mnt/") &&
988#ifdef __ANDROID_DEBUGGABLE__
989 !StartsWith(test, "/mnt/scratch") &&
990#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100991 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100992 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700993 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600994 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700995 }
996 }
997 endmntent(fp);
998
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700999 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001000 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001001 android::vold::ForceUnmount(path);
1002 }
1003
1004 return 0;
1005}
1006
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001007int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001008 int size = paths.size();
1009 for (int i = 0; i < size; i++) {
1010 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1011 true /* skipIfDirExists */);
1012 if (result != OK) {
1013 return result;
1014 }
1015 }
1016 return OK;
1017}
1018
1019int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1020 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001021 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001022 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001023 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001024 return -EINVAL;
1025 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001026
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001027 // Find the volume it belongs to
1028 auto filter_fn = [&](const VolumeBase& vol) {
1029 if (vol.getState() != VolumeBase::State::kMounted) {
1030 // The volume must be mounted
1031 return false;
1032 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001033 if (!vol.isVisibleForWrite()) {
1034 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001035 return false;
1036 }
1037 if (vol.getInternalPath().empty()) {
1038 return false;
1039 }
1040 if (vol.getMountUserId() != USER_UNKNOWN &&
1041 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1042 // The app dir must be created on a volume with the same user-id
1043 return false;
1044 }
1045 if (!path.empty() && StartsWith(path, vol.getPath())) {
1046 return true;
1047 }
1048
1049 return false;
1050 };
1051 auto volume = findVolumeWithFilter(filter_fn);
1052 if (volume == nullptr) {
1053 LOG(ERROR) << "Failed to find mounted volume for " << path;
1054 return -EINVAL;
1055 }
Zimc59d7742020-01-06 21:48:16 +00001056 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1057 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1058 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1059 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001060 const std::string lowerPath =
1061 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001062
Martijn Coenen62a4b272020-01-31 15:23:09 +01001063 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1064
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001065 const int access_result = access(lowerPath.c_str(), F_OK);
1066 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001067 // Nothing to fixup
1068 return OK;
1069 }
1070
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001071 if (skipIfDirExists && access_result == 0) {
1072 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1073 // which the dir doesn't need to have correct permission for now yet.
1074 return OK;
1075 }
1076
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001077 if (volume->getType() == VolumeBase::Type::kPublic) {
1078 // On public volumes, we don't need to setup permissions, as everything goes through
1079 // FUSE; just create the dirs and be done with it.
1080 return fs_mkdirs(lowerPath.c_str(), 0700);
1081 }
1082
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001083 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001084 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1085}
1086
1087int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001088 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001089 //sdcardfs magically does this for us
1090 return OK;
1091 }
1092 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001093}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001094
Eric Biggers7e79a432022-03-01 21:19:18 +00001095int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1096 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001097 int id = mNextObbId++;
1098
Martijn Coenend6a612a2020-11-19 10:49:45 +01001099 std::string lowerSourcePath;
1100
1101 // Convert to lower filesystem path
1102 if (StartsWith(sourcePath, "/storage/")) {
1103 auto filter_fn = [&](const VolumeBase& vol) {
1104 if (vol.getState() != VolumeBase::State::kMounted) {
1105 // The volume must be mounted
1106 return false;
1107 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001108 if (!vol.isVisibleForWrite()) {
1109 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001110 return false;
1111 }
1112 if (vol.getInternalPath().empty()) {
1113 return false;
1114 }
1115 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1116 return true;
1117 }
1118
1119 return false;
1120 };
1121 auto volume = findVolumeWithFilter(filter_fn);
1122 if (volume == nullptr) {
1123 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1124 return -EINVAL;
1125 } else {
1126 lowerSourcePath =
1127 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1128 }
1129 } else {
1130 lowerSourcePath = sourcePath;
1131 }
1132
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001133 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001134 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001135 vol->create();
1136
1137 mObbVolumes.push_back(vol);
1138 *outVolId = vol->getId();
1139 return android::OK;
1140}
1141
1142int VolumeManager::destroyObb(const std::string& volId) {
1143 auto i = mObbVolumes.begin();
1144 while (i != mObbVolumes.end()) {
1145 if ((*i)->getId() == volId) {
1146 (*i)->destroy();
1147 i = mObbVolumes.erase(i);
1148 } else {
1149 ++i;
1150 }
1151 }
1152 return android::OK;
1153}
1154
Risan8c9f3322018-10-29 08:52:56 +09001155int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1156 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001157 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001158 std::string* outVolId) {
1159 dev_t stubId = --mNextStubId;
1160 auto vol = std::shared_ptr<android::vold::StubVolume>(
1161 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001162
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001163 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001164 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1165 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001166 if (flags & android::vold::Disk::Flags::kStubVisible) {
1167 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1168 } else {
1169 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1170 }
Risan82e90de2020-02-04 16:07:21 +09001171 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001172 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001173 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001174 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001175 disk->initializePartition(vol);
1176 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001177 *outVolId = vol->getId();
1178 return android::OK;
1179}
1180
1181int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001182 auto tokens = android::base::Split(volId, ":");
1183 CHECK(tokens.size() == 2);
1184 dev_t stubId;
1185 CHECK(android::base::ParseUint(tokens[1], &stubId));
1186 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001187 return android::OK;
1188}
1189
Risan8f6198d2018-10-26 20:56:45 -06001190int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001191 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001192}
1193
Risan8f6198d2018-10-26 20:56:45 -06001194int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001195 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001196}
1197
1198int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001199 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001200}
Paul Lawrence24b7d2d2023-08-11 10:27:24 -07001201
1202android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1203 // Start with the /data mount point from fs_mgr
1204 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1205 if (entry == nullptr) {
1206 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1207 return EINVAL;
1208 }
1209
1210 // Follow any symbolic links
1211 std::string blkDevice = entry->blk_device;
1212 std::string dataDevice;
1213 if (!android::base::Realpath(blkDevice, &dataDevice)) {
1214 dataDevice = blkDevice;
1215 }
1216
1217 // Handle mapped volumes.
1218 auto& dm = android::dm::DeviceMapper::Instance();
1219 for (;;) {
1220 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1221 if (!parent.has_value()) break;
1222 dataDevice = *parent;
1223 }
1224
1225 // Get the potential /sys/block entry
1226 std::size_t leaf = dataDevice.rfind('/');
1227 if (leaf == std::string::npos) {
1228 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1229 return EINVAL;
1230 }
1231 if (dataDevice.substr(0, leaf) != "/dev/block") {
1232 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1233 return EINVAL;
1234 }
1235 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1236
1237 // Look for a directory in /sys/block containing size where the name is a shortened
1238 // version of the name we now have
1239 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1240 // Note that this directory only contains actual disks, not partitions, so this is
1241 // not going to find anything other than the disks
1242 std::string size;
1243 std::string sizeFile;
1244 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1245 if (sysfsDir.back() == '/') {
1246 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1247 return EINVAL;
1248 }
1249 sizeFile = sysfsDir + "/size";
1250 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1251 break;
1252 }
1253 }
1254
1255 // Read the size file and be done
1256 std::stringstream ssSize(size);
1257 ssSize >> *storageSize;
1258 if (ssSize.fail()) {
1259 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1260 return EINVAL;
1261 }
1262
1263 *storageSize *= 512;
1264 return OK;
1265}