blob: 21717173080c9ced4948e6bf9064caec9a02ad81 [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
Paul Lawrenced73dfd42023-08-11 10:27:24 -070038#include <android-base/file.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060041#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080042#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070043#include <android-base/strings.h>
Narayan Kamath02efdf52019-11-27 10:53:51 +000044#include <async_safe/log.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070045
Jeff Sharkey71ebe152013-09-17 17:24:38 -070046#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060047#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070048
Robert Craigb9e3ba52014-02-04 10:53:00 -050049#include <selinux/android.h>
50
San Mehatfd7f5872009-10-12 11:32:47 -070051#include <sysutils/NetlinkEvent.h>
52
Kenny Root344ca102012-04-03 17:23:01 -070053#include <private/android_filesystem_config.h>
54
Eric Biggersa701c452018-10-23 13:06:55 -070055#include <fscrypt/fscrypt.h>
Paul Lawrenced73dfd42023-08-11 10:27:24 -070056#include <libdm/dm.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070057
Risanac02a482018-10-31 21:59:47 -060058#include "AppFuseUtil.h"
Eric Biggersa701c452018-10-23 13:06:55 -070059#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080060#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070061#include "NetlinkManager.h"
62#include "Process.h"
63#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070064#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070065#include "VoldUtil.h"
66#include "VolumeManager.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070067#include "fs/Ext4.h"
68#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070069#include "model/EmulatedVolume.h"
70#include "model/ObbVolume.h"
Zima438b242019-09-25 14:37:38 +010071#include "model/PrivateVolume.h"
himanshuz0ad08622023-07-27 21:15:00 +000072#include "model/PublicVolume.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;
himanshuz0ad08622023-07-27 21:15:00 +000093using android::vold::PublicVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080094using android::vold::Symlink;
95using android::vold::Unlink;
96using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080097using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010098using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070099
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600100static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
101
102static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
103
Sudheer Shanka53947a32018-08-01 10:24:13 -0700104static const std::string kEmptyString("");
105
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600106/* 512MiB is large enough for testing purposes */
107static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700108
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700109static const unsigned int kMajorBlockMmc = 179;
110
Ricky Wai07e64a42020-02-11 14:31:24 +0000111using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
112
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700113VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700114
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700115VolumeManager* VolumeManager::Instance() {
116 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700117 return sInstance;
118}
119
120VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800121 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600122 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900123 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700124 // For security reasons, assume that a secure keyguard is
125 // showing until we hear otherwise
126 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700127}
128
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700129VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800130
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600131int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600132 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700133 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600134 if (access(kPathVirtualDisk, F_OK) != 0) {
135 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
136 }
137
138 if (mVirtualDisk == nullptr) {
139 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
140 LOG(ERROR) << "Failed to create virtual disk";
141 return -1;
142 }
143
144 struct stat buf;
145 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
146 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
147 return -1;
148 }
149
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700150 auto disk = new android::vold::Disk(
151 "virtual", buf.st_rdev, "virtual",
152 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600153 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700154 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600155 }
156 } else {
157 if (mVirtualDisk != nullptr) {
158 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700159 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600160
161 Loop::destroyByDevice(mVirtualDiskPath.c_str());
162 mVirtualDisk = nullptr;
163 }
164
165 if (access(kPathVirtualDisk, F_OK) == 0) {
166 unlink(kPathVirtualDisk);
167 }
168 }
169 return 0;
170}
171
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700172int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800173 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700174 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800175}
176
San Mehatf1b736b2009-10-10 17:22:08 -0700177int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600178 ATRACE_NAME("VolumeManager::start");
179
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700180 // Always start from a clean slate by unmounting everything in
181 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700182 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700183
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600184 Loop::destroyAll();
185
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700186 // Assume that we always have an emulated volume on internal
187 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100188 CHECK(mInternalEmulatedVolumes.empty());
189
190 auto vol = std::shared_ptr<android::vold::VolumeBase>(
191 new android::vold::EmulatedVolume("/data/media", 0));
192 vol->setMountUserId(0);
193 vol->create();
194 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700195
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600196 // Consider creating a virtual disk
197 updateVirtualDisk();
198
San Mehatf1b736b2009-10-10 17:22:08 -0700199 return 0;
200}
201
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700202void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700203 std::lock_guard<std::mutex> lock(mLock);
204
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700205 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700206 LOG(DEBUG) << "----------------";
207 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700208 evt->dump();
209 }
San Mehatf1b736b2009-10-10 17:22:08 -0700210
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700211 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
212 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700213
214 if (devType != "disk") return;
215
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600216 int major = std::stoi(evt->findParam("MAJOR"));
217 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700218 dev_t device = makedev(major, minor);
219
220 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700221 case NetlinkEvent::Action::kAdd: {
222 for (const auto& source : mDiskSources) {
223 if (source->matches(eventPath)) {
224 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700225 // specific to virtual platforms; see Utils.cpp for details)
226 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700227 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700228 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700229 flags |= android::vold::Disk::Flags::kSd;
230 } else {
231 flags |= android::vold::Disk::Flags::kUsb;
232 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700233
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700234 auto disk =
235 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
236 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
237 break;
238 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700239 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700240 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700241 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700242 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100243 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700244 handleDiskChanged(device);
245 break;
246 }
247 case NetlinkEvent::Action::kRemove: {
248 handleDiskRemoved(device);
249 break;
250 }
251 default: {
252 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
253 break;
254 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700255 }
256}
257
Jeff Sharkey401b2602017-12-14 22:15:20 -0700258void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
259 // For security reasons, if secure keyguard is showing, wait
260 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100261 // Additionally, wait until user 0 is actually started, since we need
262 // the user to be up before we can mount a FUSE daemon to handle the disk.
263 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700264 if (mSecureKeyguardShowing) {
265 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700266 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700267 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100268 } else if (!userZeroStarted) {
269 LOG(INFO) << "Found disk at " << disk->getEventPath()
270 << " but delaying scan due to user zero not having started";
271 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700272 } else {
273 disk->create();
274 mDisks.push_back(disk);
275 }
276}
277
278void VolumeManager::handleDiskChanged(dev_t device) {
279 for (const auto& disk : mDisks) {
280 if (disk->getDevice() == device) {
281 disk->readMetadata();
282 disk->readPartitions();
283 }
284 }
285
286 // For security reasons, we ignore all pending disks, since
287 // we'll scan them once the device is unlocked
288}
289
290void VolumeManager::handleDiskRemoved(dev_t device) {
291 auto i = mDisks.begin();
292 while (i != mDisks.end()) {
293 if ((*i)->getDevice() == device) {
294 (*i)->destroy();
295 i = mDisks.erase(i);
296 } else {
297 ++i;
298 }
299 }
300 auto j = mPendingDisks.begin();
301 while (j != mPendingDisks.end()) {
302 if ((*j)->getDevice() == device) {
303 j = mPendingDisks.erase(j);
304 } else {
305 ++j;
306 }
307 }
308}
309
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700310void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800311 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700312 mDiskSources.push_back(diskSource);
313}
314
315std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
316 for (auto disk : mDisks) {
317 if (disk->getId() == id) {
318 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700319 }
320 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321 return nullptr;
322}
San Mehatf1b736b2009-10-10 17:22:08 -0700323
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700324std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100325 for (const auto& vol : mInternalEmulatedVolumes) {
326 if (vol->getId() == id) {
327 return vol;
328 }
San Mehatf1b736b2009-10-10 17:22:08 -0700329 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700330 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700331 auto vol = disk->findVolume(id);
332 if (vol != nullptr) {
333 return vol;
334 }
335 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600336 for (const auto& vol : mObbVolumes) {
337 if (vol->getId() == id) {
338 return vol;
339 }
340 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700341 return nullptr;
342}
343
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800344void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
345 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700346 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700347 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700348 disk->listVolumes(type, list);
349 }
350}
351
Eric Biggers78627292023-08-01 22:36:55 +0000352bool VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700353 std::string normalizedGuid;
354 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
355 LOG(WARNING) << "Invalid GUID " << partGuid;
Eric Biggers78627292023-08-01 22:36:55 +0000356 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700357 }
358
359 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
360 if (unlink(keyPath.c_str()) != 0) {
361 LOG(ERROR) << "Failed to unlink " << keyPath;
Eric Biggers78627292023-08-01 22:36:55 +0000362 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700363 }
Eric Biggers78627292023-08-01 22:36:55 +0000364 return true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700365}
366
Zima438b242019-09-25 14:37:38 +0100367void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
368 // Destroy and remove all unstacked EmulatedVolumes for the user
369 auto i = mInternalEmulatedVolumes.begin();
370 while (i != mInternalEmulatedVolumes.end()) {
371 auto vol = *i;
372 if (vol->getMountUserId() == userId) {
373 vol->destroy();
374 i = mInternalEmulatedVolumes.erase(i);
375 } else {
376 i++;
377 }
378 }
379
380 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
381 std::list<std::string> private_vols;
382 listVolumes(VolumeBase::Type::kPrivate, private_vols);
383 for (const std::string& id : private_vols) {
384 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
385 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
386 if (pvol->getState() == VolumeBase::State::kMounted) {
387 for (const auto& vol : pvol->getVolumes()) {
388 if (vol->getMountUserId() == userId) {
389 vols_to_remove.push_back(vol);
390 }
391 }
392 for (const auto& vol : vols_to_remove) {
393 vol->destroy();
394 pvol->removeVolume(vol);
395 }
396 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
397 }
398}
399
400void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
401 // Create unstacked EmulatedVolumes for the user
402 auto vol = std::shared_ptr<android::vold::VolumeBase>(
403 new android::vold::EmulatedVolume("/data/media", userId));
404 vol->setMountUserId(userId);
405 mInternalEmulatedVolumes.push_back(vol);
406 vol->create();
407
408 // Create stacked EmulatedVolumes for the user on each PrivateVolume
409 std::list<std::string> private_vols;
410 listVolumes(VolumeBase::Type::kPrivate, private_vols);
411 for (const std::string& id : private_vols) {
412 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
413 if (pvol->getState() == VolumeBase::State::kMounted) {
414 auto evol =
415 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
416 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
417 userId));
418 evol->setMountUserId(userId);
419 pvol->addVolume(evol);
420 evol->create();
421 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
422 }
423}
424
Martijn Coenen73e30102022-07-12 08:11:02 +0000425userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
426 if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
427 return USER_UNKNOWN;
428 }
429 return mSharedStorageUser.at(userId);
430}
431
432int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
433 userid_t sharesStorageWithUserId) {
Zima438b242019-09-25 14:37:38 +0100434 LOG(INFO) << "onUserAdded: " << userId;
435
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700436 mAddedUsers[userId] = userSerialNumber;
Martijn Coenen73e30102022-07-12 08:11:02 +0000437 if (sharesStorageWithUserId != USER_UNKNOWN) {
438 mSharedStorageUser[userId] = sharesStorageWithUserId;
439 }
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700440 return 0;
441}
442
443int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100444 LOG(INFO) << "onUserRemoved: " << userId;
445
Zim2d45d9b2019-11-14 16:19:05 +0000446 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700447 mAddedUsers.erase(userId);
Martijn Coenen73e30102022-07-12 08:11:02 +0000448 mSharedStorageUser.erase(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700449 return 0;
450}
451
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700452int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100453 LOG(INFO) << "onUserStarted: " << userId;
454
Zim2d45d9b2019-11-14 16:19:05 +0000455 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
456 createEmulatedVolumesForUser(userId);
himanshuz0ad08622023-07-27 21:15:00 +0000457 std::list<std::string> public_vols;
458 listVolumes(VolumeBase::Type::kPublic, public_vols);
459 for (const std::string& id : public_vols) {
460 PublicVolume* pvol = static_cast<PublicVolume*>(findVolume(id).get());
461 if (pvol->getState() != VolumeBase::State::kMounted) {
462 continue;
463 }
464 if (pvol->isVisible() == 0) {
465 continue;
466 }
467 userid_t mountUserId = pvol->getMountUserId();
468 if (userId == mountUserId) {
469 // No need to bind mount for the user that owns the mount
470 continue;
471 }
472 if (mountUserId != VolumeManager::Instance()->getSharedStorageUser(userId)) {
473 // No need to bind if the user does not share storage with the mount owner
474 continue;
475 }
Himanshu Gupta4f179692024-05-06 11:40:19 +0100476 // Create mount directory for the user as there is a chance that no other Volume is
477 // mounted for the user (ex: if the user is just started), so /mnt/user/user_id does
478 // not exist yet.
479 auto mountDirStatus = android::vold::PrepareMountDirForUser(userId);
480 if (mountDirStatus != OK) {
481 LOG(ERROR) << "Failed to create Mount Directory for user " << userId;
482 }
himanshuz0ad08622023-07-27 21:15:00 +0000483 auto bindMountStatus = pvol->bindMountForUser(userId);
484 if (bindMountStatus != OK) {
485 LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
486 << "Failed. Error: " << bindMountStatus;
487 }
488 }
Zim2d45d9b2019-11-14 16:19:05 +0000489 }
490
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700491 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100492
493 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700494 return 0;
495}
496
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700497int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700498 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100499
Zim2d45d9b2019-11-14 16:19:05 +0000500 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100501 destroyEmulatedVolumesForUser(userId);
502 }
503
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700504 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700505 return 0;
506}
507
Martijn Coenencf5916f2020-01-03 14:36:45 +0100508void VolumeManager::createPendingDisksIfNeeded() {
509 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
510 if (!mSecureKeyguardShowing && userZeroStarted) {
511 // Now that secure keyguard has been dismissed and user 0 has
512 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700513 for (const auto& disk : mPendingDisks) {
514 disk->create();
515 mDisks.push_back(disk);
516 }
517 mPendingDisks.clear();
518 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100519}
520
521int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
522 mSecureKeyguardShowing = isShowing;
523 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700524 return 0;
525}
526
Narayan Kamath02efdf52019-11-27 10:53:51 +0000527// This code is executed after a fork so it's very important that the set of
528// methods we call here is strictly limited.
529//
530// TODO: Get rid of this guesswork altogether and instead exec a process
531// immediately after fork to do our bindding for us.
532static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000533 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000534 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000535 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000536 strerror(errno));
537 return false;
538 }
539
540 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
541 // to also protect against future changes that may cause issues across a
542 // fork.
543 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
544 errno != ENOENT) {
545 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
546 strerror(errno));
547 return false;
548 }
549
550 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
551 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000552 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000553 return false;
554 }
555
556 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
557 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000558 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000559 strerror(errno));
560 return false;
561 }
562
563 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
564 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000565 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000566 return false;
567 }
568
569 return true;
570}
571
Ricky Wai07e64a42020-02-11 14:31:24 +0000572// Fork the process and remount storage
573bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
574 int32_t mountMode = *static_cast<int32_t*>(params);
575 std::string userSource;
576 std::string storageSource;
577 pid_t child;
578 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800579 switch (mountMode) {
580 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000581 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800582 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000583 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800584 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000585 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700586 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000587 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800588 break;
Zim981222f2019-09-09 10:24:44 +0100589 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000590 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800591 default:
592 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000593 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800594 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000595 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700596
Ricky Wai07e64a42020-02-11 14:31:24 +0000597 // Fork a child to mount user-specific symlink helper into place
598 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
599 if (!(child = fork())) {
600 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
601 _exit(0);
602 } else {
603 _exit(1);
604 }
605 }
606
607 if (child == -1) {
608 PLOG(ERROR) << "Failed to fork";
609 return false;
610 } else {
611 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
612 }
613 return true;
614}
615
616// Helper function to scan all processes in /proc and call the callback if:
617// 1). pid belongs to an app process
618// 2). If input uid is 0 or it matches the process uid
619// 3). If userId is not -1 or userId matches the process userId
620bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700621 DIR* dir;
622 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600623 std::string rootName;
624 std::string pidName;
Jooyung Hana9f21712023-08-25 15:38:12 +0900625 std::string exeName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700626 int pidFd;
627 int nsFd;
628 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700629
630 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000631 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
632 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700633 }
634
635 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600636 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000637 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700638 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000639 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700640 }
641
Ricky Wai07e64a42020-02-11 14:31:24 +0000642 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700643 // Poke through all running PIDs look for apps running as UID
644 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700645 pid_t pid;
646 if (de->d_type != DT_DIR) continue;
647 if (!android::base::ParseInt(de->d_name, &pid)) continue;
648
Jeff Sharkey66270a22015-06-24 11:49:24 -0700649 pidFd = -1;
650 nsFd = -1;
651
652 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
653 if (pidFd < 0) {
654 goto next;
655 }
656 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000657 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700658 goto next;
659 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000660 if (uid != 0 && sb.st_uid != uid) {
661 goto next;
662 }
663 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700664 goto next;
665 }
666
667 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600668 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000669 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
670 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700671 goto next;
672 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600673 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700674 goto next;
675 }
676
Jooyung Hana9f21712023-08-25 15:38:12 +0900677 // Some early native processes have mount namespaces that are different
678 // from that of the init. Therefore, above check can't filter them out.
679 // Since the propagation type of / is 'shared', unmounting /storage
680 // for the early native processes affects other processes including
681 // init. Filter out such processes by skipping if a process is a
682 // non-Java process whose UID is < AID_APP_START. (The UID condition
683 // is required to not filter out child processes spawned by apps.)
684 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
685 goto next;
686 }
687 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
688 goto next;
Jiyong Park8d21c922019-01-04 13:35:25 +0900689 }
690
Jeff Sharkey66270a22015-06-24 11:49:24 -0700691 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700692 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
693 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700694 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000695 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
696 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700697 goto next;
698 }
699
Ricky Wai07e64a42020-02-11 14:31:24 +0000700 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
701 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700702 }
703
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700704 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700705 close(nsFd);
706 close(pidFd);
707 }
708 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000709 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
710 return true;
711}
712
Ricky Waia2ca11e2021-01-15 14:03:23 +0000713// In each app's namespace, unmount obb and data dirs
714static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
715 int uid, const char* targets[], int size) {
716 // This code is executed after a fork so it's very important that the set of
717 // methods we call here is strictly limited.
718 if (setns(nsFd, CLONE_NEWNS) != 0) {
719 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
720 return false;
721 }
722
723 // Unmount of Android/data/foo needs to be done before Android/data below.
724 bool result = true;
725 for (int i = 0; i < size; i++) {
726 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
727 errno != ENOENT) {
728 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
729 targets[i], strerror(errno));
730 result = false;
731 }
732 }
733
734 // Mount tmpfs on Android/data and Android/obb
735 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
736 errno != ENOENT) {
737 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
738 android_data_dir, strerror(errno));
739 result = false;
740 }
741 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
742 errno != ENOENT) {
743 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
744 android_obb_dir, strerror(errno));
745 result = false;
746 }
747 return result;
748}
749
Ricky Waie96b34f2020-05-07 16:01:33 +0100750// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
751// package dirs.
752static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
753 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000754 // This code is executed after a fork so it's very important that the set of
755 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000756 if (setns(nsFd, CLONE_NEWNS) != 0) {
757 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
758 return false;
759 }
760
Ricky Waie96b34f2020-05-07 16:01:33 +0100761 // Mount tmpfs on Android/data and Android/obb
762 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
763 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
764 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
765 android_data_dir, strerror(errno));
766 return false;
767 }
768 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
769 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
770 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
771 android_obb_dir, strerror(errno));
772 return false;
773 }
774
Ricky Wai6b122572020-02-28 16:30:47 +0000775 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100776 // Create package dir and bind mount it to the actual one.
777 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
778 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
779 targets[i], strerror(errno));
780 return false;
781 }
Ricky Wai6b122572020-02-28 16:30:47 +0000782 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
783 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
784 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000785 return false;
786 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000787 }
788 return true;
789}
790
Ricky Wai6b122572020-02-28 16:30:47 +0000791static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
792 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700793 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000794 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
795 userId, dirName.c_str(), packageName.c_str());
796 } else {
797 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
798 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000799 }
Ricky Wai6b122572020-02-28 16:30:47 +0000800}
801
802static std::string getStorageDirTarget(userid_t userId, std::string dirName,
803 std::string packageName) {
804 return StringPrintf("/storage/emulated/%d/%s/%s",
805 userId, dirName.c_str(), packageName.c_str());
806}
807
Ricky Waia2ca11e2021-01-15 14:03:23 +0000808// Fork the process and remount / unmount app data and obb dirs
809bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000810 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000811 userid_t userId = multiuser_get_user_id(uid);
812 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
813 android::base::unique_fd nsFd(
814 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
815 if (nsFd == -1) {
816 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
817 return false;
818 }
819 // Storing both Android/obb and Android/data paths.
820 int size = packageNames.size() * 2;
821
822 std::unique_ptr<std::string[]> sources(new std::string[size]);
823 std::unique_ptr<std::string[]> targets(new std::string[size]);
824 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
825 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
826 const char** sources_cstr = sources_uptr.get();
827 const char** targets_cstr = targets_uptr.get();
828
829 for (int i = 0; i < size; i += 2) {
830 std::string const& packageName = packageNames[i/2];
831 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
832 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
833 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
834 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
835
836 sources_cstr[i] = sources[i].c_str();
837 targets_cstr[i] = targets[i].c_str();
838 sources_cstr[i+1] = sources[i+1].c_str();
839 targets_cstr[i+1] = targets[i+1].c_str();
840 }
841
842 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000843 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000844 // This needs to be done before EnsureDirExists to ensure Android/ is created.
845 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000846 if (status != OK) {
847 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
848 return false;
849 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000850 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
851 if (status != OK) {
852 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
853 return false;
854 }
Ricky Wai6b122572020-02-28 16:30:47 +0000855 }
856
Ricky Waie96b34f2020-05-07 16:01:33 +0100857 char android_data_dir[PATH_MAX];
858 char android_obb_dir[PATH_MAX];
859 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
860 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
861
Ricky Wai6b122572020-02-28 16:30:47 +0000862 pid_t child;
863 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
864 // original vold process mount namespace.
865 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000866 if (doUnmount) {
867 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
868 targets_cstr, size)) {
869 _exit(0);
870 } else {
871 _exit(1);
872 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000873 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000874 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
875 sources_cstr, targets_cstr, size)) {
876 _exit(0);
877 } else {
878 _exit(1);
879 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000880 }
881 }
Ricky Wai6b122572020-02-28 16:30:47 +0000882
Ricky Wai07e64a42020-02-11 14:31:24 +0000883 if (child == -1) {
884 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000885 return false;
886 } else {
887 int status;
888 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
889 PLOG(ERROR) << "Failed to waitpid: " << child;
890 return false;
891 }
892 if (!WIFEXITED(status)) {
893 PLOG(ERROR) << "Process did not exit normally, status: " << status;
894 return false;
895 }
896 if (WEXITSTATUS(status)) {
897 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
898 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000899 }
900 }
Ricky Wai6b122572020-02-28 16:30:47 +0000901 return true;
902}
903
Ricky Waia2ca11e2021-01-15 14:03:23 +0000904int VolumeManager::handleAppStorageDirs(int uid, int pid,
905 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000906 // Only run the remount if fuse is mounted for that user.
907 userid_t userId = multiuser_get_user_id(uid);
908 bool fuseMounted = false;
909 for (auto& vol : mInternalEmulatedVolumes) {
910 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
911 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
912 if (emulatedVol) {
913 fuseMounted = emulatedVol->isFuseMounted();
914 }
915 break;
916 }
917 }
918 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000919 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000920 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700921 return 0;
922}
923
Martijn Coenen23c04452020-04-29 07:49:41 +0200924int VolumeManager::abortFuse() {
925 return android::vold::AbortFuseConnections();
926}
927
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700928int VolumeManager::reset() {
929 // Tear down all existing disks/volumes and start from a blank slate so
930 // newly connected framework hears all events.
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900931
932 // Destroy StubVolume disks. This needs to be done before destroying
933 // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
934 // directory (which is in a StubVolume) is bind-mounted to
935 // /data/media/0/Download.
936 // We do not recreate StubVolumes here because they are managed from outside
937 // Android (e.g. from ChromeOS) and their disk recreation on reset events
938 // should be handled from outside by calling createStubVolume() again.
939 for (const auto& disk : mDisks) {
940 if (disk->isStub()) {
941 disk->destroy();
942 }
943 }
944 // Remove StubVolume from both mDisks and mPendingDisks.
945 const auto isStub = [](const auto& disk) { return disk->isStub(); };
946 mDisks.remove_if(isStub);
947 mPendingDisks.remove_if(isStub);
948
Zima438b242019-09-25 14:37:38 +0100949 for (const auto& vol : mInternalEmulatedVolumes) {
950 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800951 }
Zima438b242019-09-25 14:37:38 +0100952 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100953
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900954 // Destroy and recreate non-StubVolume disks.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700955 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700956 disk->destroy();
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900957 disk->create();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700958 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900959
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600960 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700961 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800962 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +0000963 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +0100964
965 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
966 // with FUSE fds open.
967 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700968 return 0;
969}
970
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700971// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700972int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100973 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700974 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700975 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700976 android::vold::sSleepOnUnmount = false;
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900977 // Destroy StubVolume disks before destroying EmulatedVolumes (see the
978 // comment in VolumeManager::reset()).
979 for (const auto& disk : mDisks) {
980 if (disk->isStub()) {
981 disk->destroy();
982 }
983 }
Zima438b242019-09-25 14:37:38 +0100984 for (const auto& vol : mInternalEmulatedVolumes) {
985 vol->destroy();
986 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700987 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900988 if (!disk->isStub()) {
989 disk->destroy();
990 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700991 }
Zima438b242019-09-25 14:37:38 +0100992
993 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700994 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700995 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700996 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200997
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700998 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700999}
1000
Jeff Sharkey9c484982015-03-31 10:35:33 -07001001int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001002 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001003 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001004
Jeff Sharkey9c484982015-03-31 10:35:33 -07001005 // First, try gracefully unmounting all known devices
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001006 // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
1007 // comment in VolumeManager::reset()).
1008 for (const auto& disk : mDisks) {
1009 if (disk->isStub()) {
1010 disk->unmountAll();
1011 }
1012 }
Zima438b242019-09-25 14:37:38 +01001013 for (const auto& vol : mInternalEmulatedVolumes) {
1014 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -07001015 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001016 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001017 if (!disk->isStub()) {
1018 disk->unmountAll();
1019 }
Jeff Sharkey9c484982015-03-31 10:35:33 -07001020 }
1021
1022 // Worst case we might have some stale mounts lurking around, so
1023 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001024 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001025 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001026 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001027 return -errno;
1028 }
1029
1030 // Some volumes can be stacked on each other, so force unmount in
1031 // reverse order to give us the best chance of success.
1032 std::list<std::string> toUnmount;
1033 mntent* mentry;
1034 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001035 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001036 if ((StartsWith(test, "/mnt/") &&
1037#ifdef __ANDROID_DEBUGGABLE__
1038 !StartsWith(test, "/mnt/scratch") &&
1039#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +01001040 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +01001041 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001042 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001043 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001044 }
1045 }
1046 endmntent(fp);
1047
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001048 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001049 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001050 android::vold::ForceUnmount(path);
1051 }
1052
1053 return 0;
1054}
1055
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001056int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001057 int size = paths.size();
1058 for (int i = 0; i < size; i++) {
1059 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1060 true /* skipIfDirExists */);
1061 if (result != OK) {
1062 return result;
1063 }
1064 }
1065 return OK;
1066}
1067
1068int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1069 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001070 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001071 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001072 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001073 return -EINVAL;
1074 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001075
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001076 // Find the volume it belongs to
1077 auto filter_fn = [&](const VolumeBase& vol) {
1078 if (vol.getState() != VolumeBase::State::kMounted) {
1079 // The volume must be mounted
1080 return false;
1081 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001082 if (!vol.isVisibleForWrite()) {
1083 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001084 return false;
1085 }
1086 if (vol.getInternalPath().empty()) {
1087 return false;
1088 }
1089 if (vol.getMountUserId() != USER_UNKNOWN &&
1090 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1091 // The app dir must be created on a volume with the same user-id
1092 return false;
1093 }
1094 if (!path.empty() && StartsWith(path, vol.getPath())) {
1095 return true;
1096 }
1097
1098 return false;
1099 };
1100 auto volume = findVolumeWithFilter(filter_fn);
1101 if (volume == nullptr) {
1102 LOG(ERROR) << "Failed to find mounted volume for " << path;
1103 return -EINVAL;
1104 }
Zimc59d7742020-01-06 21:48:16 +00001105 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1106 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1107 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1108 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001109 const std::string lowerPath =
1110 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001111
Martijn Coenen62a4b272020-01-31 15:23:09 +01001112 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1113
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001114 const int access_result = access(lowerPath.c_str(), F_OK);
1115 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001116 // Nothing to fixup
1117 return OK;
1118 }
1119
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001120 if (skipIfDirExists && access_result == 0) {
1121 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1122 // which the dir doesn't need to have correct permission for now yet.
1123 return OK;
1124 }
1125
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001126 if (volume->getType() == VolumeBase::Type::kPublic) {
1127 // On public volumes, we don't need to setup permissions, as everything goes through
1128 // FUSE; just create the dirs and be done with it.
1129 return fs_mkdirs(lowerPath.c_str(), 0700);
1130 }
1131
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001132 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001133 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1134}
1135
1136int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001137 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001138 //sdcardfs magically does this for us
1139 return OK;
1140 }
1141 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001142}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001143
Eric Biggers7e79a432022-03-01 21:19:18 +00001144int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1145 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001146 int id = mNextObbId++;
1147
Martijn Coenend6a612a2020-11-19 10:49:45 +01001148 std::string lowerSourcePath;
1149
1150 // Convert to lower filesystem path
1151 if (StartsWith(sourcePath, "/storage/")) {
1152 auto filter_fn = [&](const VolumeBase& vol) {
1153 if (vol.getState() != VolumeBase::State::kMounted) {
1154 // The volume must be mounted
1155 return false;
1156 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001157 if (!vol.isVisibleForWrite()) {
1158 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001159 return false;
1160 }
1161 if (vol.getInternalPath().empty()) {
1162 return false;
1163 }
1164 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1165 return true;
1166 }
1167
1168 return false;
1169 };
1170 auto volume = findVolumeWithFilter(filter_fn);
1171 if (volume == nullptr) {
1172 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1173 return -EINVAL;
1174 } else {
1175 lowerSourcePath =
1176 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1177 }
1178 } else {
1179 lowerSourcePath = sourcePath;
1180 }
1181
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001182 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001183 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001184 vol->create();
1185
1186 mObbVolumes.push_back(vol);
1187 *outVolId = vol->getId();
1188 return android::OK;
1189}
1190
1191int VolumeManager::destroyObb(const std::string& volId) {
1192 auto i = mObbVolumes.begin();
1193 while (i != mObbVolumes.end()) {
1194 if ((*i)->getId() == volId) {
1195 (*i)->destroy();
1196 i = mObbVolumes.erase(i);
1197 } else {
1198 ++i;
1199 }
1200 }
1201 return android::OK;
1202}
1203
Risan8c9f3322018-10-29 08:52:56 +09001204int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1205 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001206 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001207 std::string* outVolId) {
1208 dev_t stubId = --mNextStubId;
1209 auto vol = std::shared_ptr<android::vold::StubVolume>(
1210 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001211
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001212 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001213 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1214 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001215 if (flags & android::vold::Disk::Flags::kStubVisible) {
1216 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1217 } else {
1218 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1219 }
Risan82e90de2020-02-04 16:07:21 +09001220 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001221 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001222 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001223 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001224 disk->initializePartition(vol);
1225 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001226 *outVolId = vol->getId();
1227 return android::OK;
1228}
1229
1230int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001231 auto tokens = android::base::Split(volId, ":");
1232 CHECK(tokens.size() == 2);
1233 dev_t stubId;
1234 CHECK(android::base::ParseUint(tokens[1], &stubId));
1235 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001236 return android::OK;
1237}
1238
Risan8f6198d2018-10-26 20:56:45 -06001239int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001240 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001241}
1242
Risan8f6198d2018-10-26 20:56:45 -06001243int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001244 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001245}
1246
1247int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001248 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001249}
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001250
1251android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1252 // Start with the /data mount point from fs_mgr
1253 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1254 if (entry == nullptr) {
1255 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1256 return EINVAL;
1257 }
1258
1259 // Follow any symbolic links
1260 std::string blkDevice = entry->blk_device;
1261 std::string dataDevice;
1262 if (!android::base::Realpath(blkDevice, &dataDevice)) {
1263 dataDevice = blkDevice;
1264 }
1265
1266 // Handle mapped volumes.
1267 auto& dm = android::dm::DeviceMapper::Instance();
1268 for (;;) {
1269 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1270 if (!parent.has_value()) break;
1271 dataDevice = *parent;
1272 }
1273
1274 // Get the potential /sys/block entry
1275 std::size_t leaf = dataDevice.rfind('/');
1276 if (leaf == std::string::npos) {
1277 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1278 return EINVAL;
1279 }
1280 if (dataDevice.substr(0, leaf) != "/dev/block") {
1281 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1282 return EINVAL;
1283 }
1284 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1285
1286 // Look for a directory in /sys/block containing size where the name is a shortened
1287 // version of the name we now have
1288 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1289 // Note that this directory only contains actual disks, not partitions, so this is
1290 // not going to find anything other than the disks
1291 std::string size;
1292 std::string sizeFile;
1293 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1294 if (sysfsDir.back() == '/') {
1295 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1296 return EINVAL;
1297 }
1298 sizeFile = sysfsDir + "/size";
1299 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1300 break;
1301 }
1302 }
1303
1304 // Read the size file and be done
1305 std::stringstream ssSize(size);
1306 ssSize >> *storageSize;
1307 if (ssSize.fail()) {
1308 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1309 return EINVAL;
1310 }
1311
1312 *storageSize *= 512;
1313 return OK;
1314}