blob: 49a8b2b85ff510f324a22e19e31e98abfebe27ef [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
104/* 512MiB is large enough for testing purposes */
105static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700106
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700107static const unsigned int kMajorBlockMmc = 179;
108
Ricky Wai07e64a42020-02-11 14:31:24 +0000109using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
110
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700111VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700112
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700113VolumeManager* VolumeManager::Instance() {
114 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700115 return sInstance;
116}
117
118VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800119 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600120 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900121 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700122 // For security reasons, assume that a secure keyguard is
123 // showing until we hear otherwise
124 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700125}
126
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700127VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800128
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600130 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700131 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600132 if (access(kPathVirtualDisk, F_OK) != 0) {
133 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
134 }
135
136 if (mVirtualDisk == nullptr) {
137 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
138 LOG(ERROR) << "Failed to create virtual disk";
139 return -1;
140 }
141
142 struct stat buf;
143 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
144 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
145 return -1;
146 }
147
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700148 auto disk = new android::vold::Disk(
149 "virtual", buf.st_rdev, "virtual",
150 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600151 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700152 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600153 }
154 } else {
155 if (mVirtualDisk != nullptr) {
156 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700157 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600158
159 Loop::destroyByDevice(mVirtualDiskPath.c_str());
160 mVirtualDisk = nullptr;
161 }
162
163 if (access(kPathVirtualDisk, F_OK) == 0) {
164 unlink(kPathVirtualDisk);
165 }
166 }
167 return 0;
168}
169
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700170int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800171 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700172 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800173}
174
San Mehatf1b736b2009-10-10 17:22:08 -0700175int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600176 ATRACE_NAME("VolumeManager::start");
177
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700178 // Always start from a clean slate by unmounting everything in
179 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700180 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700181
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600182 Loop::destroyAll();
183
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700184 // Assume that we always have an emulated volume on internal
185 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100186 CHECK(mInternalEmulatedVolumes.empty());
187
188 auto vol = std::shared_ptr<android::vold::VolumeBase>(
189 new android::vold::EmulatedVolume("/data/media", 0));
190 vol->setMountUserId(0);
191 vol->create();
192 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700193
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600194 // Consider creating a virtual disk
195 updateVirtualDisk();
196
San Mehatf1b736b2009-10-10 17:22:08 -0700197 return 0;
198}
199
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700200void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700201 std::lock_guard<std::mutex> lock(mLock);
202
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700203 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700204 LOG(DEBUG) << "----------------";
205 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700206 evt->dump();
207 }
San Mehatf1b736b2009-10-10 17:22:08 -0700208
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700209 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
210 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700211
212 if (devType != "disk") return;
213
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600214 int major = std::stoi(evt->findParam("MAJOR"));
215 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700216 dev_t device = makedev(major, minor);
217
218 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700219 case NetlinkEvent::Action::kAdd: {
220 for (const auto& source : mDiskSources) {
221 if (source->matches(eventPath)) {
222 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700223 // specific to virtual platforms; see Utils.cpp for details)
224 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700225 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700226 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700227 flags |= android::vold::Disk::Flags::kSd;
228 } else {
229 flags |= android::vold::Disk::Flags::kUsb;
230 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700231
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700232 auto disk =
233 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
234 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
235 break;
236 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700237 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700238 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700239 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700240 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100241 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700242 handleDiskChanged(device);
243 break;
244 }
245 case NetlinkEvent::Action::kRemove: {
246 handleDiskRemoved(device);
247 break;
248 }
249 default: {
250 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
251 break;
252 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700253 }
254}
255
Jeff Sharkey401b2602017-12-14 22:15:20 -0700256void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
257 // For security reasons, if secure keyguard is showing, wait
258 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100259 // Additionally, wait until user 0 is actually started, since we need
260 // the user to be up before we can mount a FUSE daemon to handle the disk.
261 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700262 if (mSecureKeyguardShowing) {
263 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700264 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700265 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100266 } else if (!userZeroStarted) {
267 LOG(INFO) << "Found disk at " << disk->getEventPath()
268 << " but delaying scan due to user zero not having started";
269 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700270 } else {
271 disk->create();
272 mDisks.push_back(disk);
273 }
274}
275
276void VolumeManager::handleDiskChanged(dev_t device) {
277 for (const auto& disk : mDisks) {
278 if (disk->getDevice() == device) {
279 disk->readMetadata();
280 disk->readPartitions();
281 }
282 }
283
284 // For security reasons, we ignore all pending disks, since
285 // we'll scan them once the device is unlocked
286}
287
288void VolumeManager::handleDiskRemoved(dev_t device) {
289 auto i = mDisks.begin();
290 while (i != mDisks.end()) {
291 if ((*i)->getDevice() == device) {
292 (*i)->destroy();
293 i = mDisks.erase(i);
294 } else {
295 ++i;
296 }
297 }
298 auto j = mPendingDisks.begin();
299 while (j != mPendingDisks.end()) {
300 if ((*j)->getDevice() == device) {
301 j = mPendingDisks.erase(j);
302 } else {
303 ++j;
304 }
305 }
306}
307
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700308void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800309 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700310 mDiskSources.push_back(diskSource);
311}
312
313std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
314 for (auto disk : mDisks) {
315 if (disk->getId() == id) {
316 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700317 }
318 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700319 return nullptr;
320}
San Mehatf1b736b2009-10-10 17:22:08 -0700321
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700322std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100323 for (const auto& vol : mInternalEmulatedVolumes) {
324 if (vol->getId() == id) {
325 return vol;
326 }
San Mehatf1b736b2009-10-10 17:22:08 -0700327 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700328 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700329 auto vol = disk->findVolume(id);
330 if (vol != nullptr) {
331 return vol;
332 }
333 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600334 for (const auto& vol : mObbVolumes) {
335 if (vol->getId() == id) {
336 return vol;
337 }
338 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700339 return nullptr;
340}
341
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800342void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
343 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700344 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700345 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700346 disk->listVolumes(type, list);
347 }
348}
349
Eric Biggers78627292023-08-01 22:36:55 +0000350bool VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700351 std::string normalizedGuid;
352 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
353 LOG(WARNING) << "Invalid GUID " << partGuid;
Eric Biggers78627292023-08-01 22:36:55 +0000354 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700355 }
356
357 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
358 if (unlink(keyPath.c_str()) != 0) {
359 LOG(ERROR) << "Failed to unlink " << keyPath;
Eric Biggers78627292023-08-01 22:36:55 +0000360 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700361 }
Eric Biggers78627292023-08-01 22:36:55 +0000362 return true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700363}
364
Zima438b242019-09-25 14:37:38 +0100365void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
366 // Destroy and remove all unstacked EmulatedVolumes for the user
367 auto i = mInternalEmulatedVolumes.begin();
368 while (i != mInternalEmulatedVolumes.end()) {
369 auto vol = *i;
370 if (vol->getMountUserId() == userId) {
371 vol->destroy();
372 i = mInternalEmulatedVolumes.erase(i);
373 } else {
374 i++;
375 }
376 }
377
378 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
379 std::list<std::string> private_vols;
380 listVolumes(VolumeBase::Type::kPrivate, private_vols);
381 for (const std::string& id : private_vols) {
382 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
383 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
384 if (pvol->getState() == VolumeBase::State::kMounted) {
385 for (const auto& vol : pvol->getVolumes()) {
386 if (vol->getMountUserId() == userId) {
387 vols_to_remove.push_back(vol);
388 }
389 }
390 for (const auto& vol : vols_to_remove) {
391 vol->destroy();
392 pvol->removeVolume(vol);
393 }
394 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
395 }
396}
397
398void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
399 // Create unstacked EmulatedVolumes for the user
400 auto vol = std::shared_ptr<android::vold::VolumeBase>(
401 new android::vold::EmulatedVolume("/data/media", userId));
402 vol->setMountUserId(userId);
403 mInternalEmulatedVolumes.push_back(vol);
404 vol->create();
405
406 // Create stacked EmulatedVolumes for the user on each PrivateVolume
407 std::list<std::string> private_vols;
408 listVolumes(VolumeBase::Type::kPrivate, private_vols);
409 for (const std::string& id : private_vols) {
410 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
411 if (pvol->getState() == VolumeBase::State::kMounted) {
412 auto evol =
413 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
414 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
415 userId));
416 evol->setMountUserId(userId);
417 pvol->addVolume(evol);
418 evol->create();
419 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
420 }
421}
422
Martijn Coenen73e30102022-07-12 08:11:02 +0000423userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
424 if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
425 return USER_UNKNOWN;
426 }
427 return mSharedStorageUser.at(userId);
428}
429
430int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
431 userid_t sharesStorageWithUserId) {
Zima438b242019-09-25 14:37:38 +0100432 LOG(INFO) << "onUserAdded: " << userId;
433
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700434 mAddedUsers[userId] = userSerialNumber;
Martijn Coenen73e30102022-07-12 08:11:02 +0000435 if (sharesStorageWithUserId != USER_UNKNOWN) {
436 mSharedStorageUser[userId] = sharesStorageWithUserId;
437 }
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700438 return 0;
439}
440
441int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100442 LOG(INFO) << "onUserRemoved: " << userId;
443
Zim2d45d9b2019-11-14 16:19:05 +0000444 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700445 mAddedUsers.erase(userId);
Martijn Coenen73e30102022-07-12 08:11:02 +0000446 mSharedStorageUser.erase(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700447 return 0;
448}
449
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700450int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100451 LOG(INFO) << "onUserStarted: " << userId;
452
Zim2d45d9b2019-11-14 16:19:05 +0000453 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
454 createEmulatedVolumesForUser(userId);
Omar Eissad9c4b232025-03-13 11:52:43 +0000455
456 userid_t sharedStorageUserId = VolumeManager::Instance()->getSharedStorageUser(userId);
457 if (sharedStorageUserId != USER_UNKNOWN) {
458 std::list<std::string> public_vols;
459 listVolumes(VolumeBase::Type::kPublic, public_vols);
460 for (const std::string& id : public_vols) {
461 PublicVolume *pvol = static_cast<PublicVolume *>(findVolume(id).get());
462 if (pvol->getState() != VolumeBase::State::kMounted) {
463 continue;
464 }
465 if (pvol->isVisible() == 0) {
466 continue;
467 }
468 userid_t mountUserId = pvol->getMountUserId();
469 if (userId == mountUserId) {
470 // No need to bind mount for the user that owns the mount
471 continue;
472 }
473
474 if (mountUserId != sharedStorageUserId) {
475 // No need to bind if the user does not share storage with the mount owner
476 continue;
477 }
478 // Create mount directory for the user as there is a chance that no other Volume is
479 // mounted for the user (ex: if the user is just started),
480 // so /mnt/user/user_id does not exist yet.
481 auto mountDirStatus = android::vold::PrepareMountDirForUser(userId);
482 if (mountDirStatus != OK) {
483 LOG(ERROR) << "Failed to create Mount Directory for user " << userId;
484 }
485 auto bindMountStatus = pvol->bindMountForUser(userId);
486 if (bindMountStatus != OK) {
487 LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
488 << "Failed. Error: " << bindMountStatus;
489 }
himanshuz0ad08622023-07-27 21:15:00 +0000490 }
491 }
Zim2d45d9b2019-11-14 16:19:05 +0000492 }
493
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700494 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100495
496 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700497 return 0;
498}
499
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700500int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700501 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100502
Zim2d45d9b2019-11-14 16:19:05 +0000503 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100504 destroyEmulatedVolumesForUser(userId);
Omar Eissad9c4b232025-03-13 11:52:43 +0000505
506 userid_t sharedStorageUserId = VolumeManager::Instance()->getSharedStorageUser(userId);
507 if (sharedStorageUserId != USER_UNKNOWN) {
508 std::list<std::string> public_vols;
509 listVolumes(VolumeBase::Type::kPublic, public_vols);
510 for (const std::string &id: public_vols) {
511 PublicVolume *pvol = static_cast<PublicVolume *>(findVolume(id).get());
512 if (pvol->getState() != VolumeBase::State::kMounted) {
513 continue;
514 }
515 if (pvol->isVisible() == 0) {
516 continue;
517 }
518 userid_t mountUserId = pvol->getMountUserId();
519 if (userId == mountUserId) {
520 // No need to remove bind mount for the user that owns the mount
521 continue;
522 }
523 if (mountUserId != sharedStorageUserId) {
524 // No need to remove bind mount
525 // if the user does not share storage with the mount owner
526 continue;
527 }
528 LOG(INFO) << "Removing Public Volume Bind Mount for: " << userId;
529 auto mountPath = GetFuseMountPathForUser(userId, pvol->getStableName());
530 android::vold::ForceUnmount(mountPath);
531 rmdir(mountPath.c_str());
532 }
533 }
534
Zima438b242019-09-25 14:37:38 +0100535 }
536
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700537 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700538 return 0;
539}
540
Martijn Coenencf5916f2020-01-03 14:36:45 +0100541void VolumeManager::createPendingDisksIfNeeded() {
542 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
543 if (!mSecureKeyguardShowing && userZeroStarted) {
544 // Now that secure keyguard has been dismissed and user 0 has
545 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700546 for (const auto& disk : mPendingDisks) {
547 disk->create();
548 mDisks.push_back(disk);
549 }
550 mPendingDisks.clear();
551 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100552}
553
554int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
555 mSecureKeyguardShowing = isShowing;
556 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700557 return 0;
558}
559
Narayan Kamath02efdf52019-11-27 10:53:51 +0000560// This code is executed after a fork so it's very important that the set of
561// methods we call here is strictly limited.
562//
563// TODO: Get rid of this guesswork altogether and instead exec a process
564// immediately after fork to do our bindding for us.
565static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000566 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000567 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000568 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000569 strerror(errno));
570 return false;
571 }
572
573 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
574 // to also protect against future changes that may cause issues across a
575 // fork.
576 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
577 errno != ENOENT) {
578 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
579 strerror(errno));
580 return false;
581 }
582
583 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
584 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000585 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000586 return false;
587 }
588
589 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
590 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000591 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000592 strerror(errno));
593 return false;
594 }
595
596 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
597 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000598 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000599 return false;
600 }
601
602 return true;
603}
604
Ricky Wai07e64a42020-02-11 14:31:24 +0000605// Fork the process and remount storage
606bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
607 int32_t mountMode = *static_cast<int32_t*>(params);
608 std::string userSource;
609 std::string storageSource;
610 pid_t child;
611 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800612 switch (mountMode) {
613 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000614 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800615 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000616 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800617 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000618 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700619 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000620 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800621 break;
Zim981222f2019-09-09 10:24:44 +0100622 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000623 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800624 default:
625 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000626 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800627 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000628 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700629
Ricky Wai07e64a42020-02-11 14:31:24 +0000630 // Fork a child to mount user-specific symlink helper into place
631 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
632 if (!(child = fork())) {
633 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
634 _exit(0);
635 } else {
636 _exit(1);
637 }
638 }
639
640 if (child == -1) {
641 PLOG(ERROR) << "Failed to fork";
642 return false;
643 } else {
644 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
645 }
646 return true;
647}
648
649// Helper function to scan all processes in /proc and call the callback if:
650// 1). pid belongs to an app process
651// 2). If input uid is 0 or it matches the process uid
652// 3). If userId is not -1 or userId matches the process userId
653bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700654 DIR* dir;
655 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600656 std::string rootName;
657 std::string pidName;
Jooyung Hana9f21712023-08-25 15:38:12 +0900658 std::string exeName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700659 int pidFd;
660 int nsFd;
661 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700662
663 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000664 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
665 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700666 }
667
668 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600669 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000670 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700671 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000672 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700673 }
674
Ricky Wai07e64a42020-02-11 14:31:24 +0000675 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700676 // Poke through all running PIDs look for apps running as UID
677 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700678 pid_t pid;
679 if (de->d_type != DT_DIR) continue;
680 if (!android::base::ParseInt(de->d_name, &pid)) continue;
681
Jeff Sharkey66270a22015-06-24 11:49:24 -0700682 pidFd = -1;
683 nsFd = -1;
684
685 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
686 if (pidFd < 0) {
687 goto next;
688 }
689 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000690 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700691 goto next;
692 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000693 if (uid != 0 && sb.st_uid != uid) {
694 goto next;
695 }
696 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700697 goto next;
698 }
699
700 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600701 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000702 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
703 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700704 goto next;
705 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600706 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700707 goto next;
708 }
709
Jooyung Hana9f21712023-08-25 15:38:12 +0900710 // Some early native processes have mount namespaces that are different
711 // from that of the init. Therefore, above check can't filter them out.
712 // Since the propagation type of / is 'shared', unmounting /storage
713 // for the early native processes affects other processes including
714 // init. Filter out such processes by skipping if a process is a
715 // non-Java process whose UID is < AID_APP_START. (The UID condition
716 // is required to not filter out child processes spawned by apps.)
717 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
718 goto next;
719 }
720 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
721 goto next;
Jiyong Park8d21c922019-01-04 13:35:25 +0900722 }
723
Jeff Sharkey66270a22015-06-24 11:49:24 -0700724 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700725 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
726 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700727 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000728 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
729 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700730 goto next;
731 }
732
Ricky Wai07e64a42020-02-11 14:31:24 +0000733 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
734 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700735 }
736
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700737 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700738 close(nsFd);
739 close(pidFd);
740 }
741 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000742 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
743 return true;
744}
745
Ricky Waia2ca11e2021-01-15 14:03:23 +0000746// In each app's namespace, unmount obb and data dirs
747static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
748 int uid, const char* targets[], int size) {
749 // This code is executed after a fork so it's very important that the set of
750 // methods we call here is strictly limited.
751 if (setns(nsFd, CLONE_NEWNS) != 0) {
752 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
753 return false;
754 }
755
756 // Unmount of Android/data/foo needs to be done before Android/data below.
757 bool result = true;
758 for (int i = 0; i < size; i++) {
759 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
760 errno != ENOENT) {
761 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
762 targets[i], strerror(errno));
763 result = false;
764 }
765 }
766
767 // Mount tmpfs on Android/data and Android/obb
768 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
769 errno != ENOENT) {
770 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
771 android_data_dir, strerror(errno));
772 result = false;
773 }
774 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
775 errno != ENOENT) {
776 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
777 android_obb_dir, strerror(errno));
778 result = false;
779 }
780 return result;
781}
782
Ricky Waie96b34f2020-05-07 16:01:33 +0100783// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
784// package dirs.
785static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
786 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000787 // This code is executed after a fork so it's very important that the set of
788 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000789 if (setns(nsFd, CLONE_NEWNS) != 0) {
790 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
791 return false;
792 }
793
Ricky Waie96b34f2020-05-07 16:01:33 +0100794 // Mount tmpfs on Android/data and Android/obb
795 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
796 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
797 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
798 android_data_dir, strerror(errno));
799 return false;
800 }
801 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
802 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
803 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
804 android_obb_dir, strerror(errno));
805 return false;
806 }
807
Ricky Wai6b122572020-02-28 16:30:47 +0000808 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100809 // Create package dir and bind mount it to the actual one.
810 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
811 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
812 targets[i], strerror(errno));
813 return false;
814 }
Ricky Wai6b122572020-02-28 16:30:47 +0000815 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
816 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
817 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000818 return false;
819 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000820 }
821 return true;
822}
823
Ricky Wai6b122572020-02-28 16:30:47 +0000824static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
825 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700826 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000827 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
828 userId, dirName.c_str(), packageName.c_str());
829 } else {
830 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
831 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000832 }
Ricky Wai6b122572020-02-28 16:30:47 +0000833}
834
835static std::string getStorageDirTarget(userid_t userId, std::string dirName,
836 std::string packageName) {
837 return StringPrintf("/storage/emulated/%d/%s/%s",
838 userId, dirName.c_str(), packageName.c_str());
839}
840
Ricky Waia2ca11e2021-01-15 14:03:23 +0000841// Fork the process and remount / unmount app data and obb dirs
842bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000843 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000844 userid_t userId = multiuser_get_user_id(uid);
845 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
846 android::base::unique_fd nsFd(
847 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
848 if (nsFd == -1) {
849 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
850 return false;
851 }
852 // Storing both Android/obb and Android/data paths.
853 int size = packageNames.size() * 2;
854
855 std::unique_ptr<std::string[]> sources(new std::string[size]);
856 std::unique_ptr<std::string[]> targets(new std::string[size]);
857 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
858 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
859 const char** sources_cstr = sources_uptr.get();
860 const char** targets_cstr = targets_uptr.get();
861
862 for (int i = 0; i < size; i += 2) {
863 std::string const& packageName = packageNames[i/2];
864 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
865 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
866 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
867 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
868
869 sources_cstr[i] = sources[i].c_str();
870 targets_cstr[i] = targets[i].c_str();
871 sources_cstr[i+1] = sources[i+1].c_str();
872 targets_cstr[i+1] = targets[i+1].c_str();
873 }
874
875 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000876 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000877 // This needs to be done before EnsureDirExists to ensure Android/ is created.
878 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000879 if (status != OK) {
880 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
881 return false;
882 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000883 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
884 if (status != OK) {
885 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
886 return false;
887 }
Ricky Wai6b122572020-02-28 16:30:47 +0000888 }
889
Ricky Waie96b34f2020-05-07 16:01:33 +0100890 char android_data_dir[PATH_MAX];
891 char android_obb_dir[PATH_MAX];
892 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
893 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
894
Ricky Wai6b122572020-02-28 16:30:47 +0000895 pid_t child;
896 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
897 // original vold process mount namespace.
898 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000899 if (doUnmount) {
900 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
901 targets_cstr, size)) {
902 _exit(0);
903 } else {
904 _exit(1);
905 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000906 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000907 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
908 sources_cstr, targets_cstr, size)) {
909 _exit(0);
910 } else {
911 _exit(1);
912 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000913 }
914 }
Ricky Wai6b122572020-02-28 16:30:47 +0000915
Ricky Wai07e64a42020-02-11 14:31:24 +0000916 if (child == -1) {
917 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000918 return false;
919 } else {
920 int status;
921 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
922 PLOG(ERROR) << "Failed to waitpid: " << child;
923 return false;
924 }
925 if (!WIFEXITED(status)) {
926 PLOG(ERROR) << "Process did not exit normally, status: " << status;
927 return false;
928 }
929 if (WEXITSTATUS(status)) {
930 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
931 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000932 }
933 }
Ricky Wai6b122572020-02-28 16:30:47 +0000934 return true;
935}
936
Ricky Waia2ca11e2021-01-15 14:03:23 +0000937int VolumeManager::handleAppStorageDirs(int uid, int pid,
938 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000939 // Only run the remount if fuse is mounted for that user.
940 userid_t userId = multiuser_get_user_id(uid);
941 bool fuseMounted = false;
942 for (auto& vol : mInternalEmulatedVolumes) {
943 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
944 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
945 if (emulatedVol) {
946 fuseMounted = emulatedVol->isFuseMounted();
947 }
948 break;
949 }
950 }
951 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000952 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000953 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700954 return 0;
955}
956
Martijn Coenen23c04452020-04-29 07:49:41 +0200957int VolumeManager::abortFuse() {
958 return android::vold::AbortFuseConnections();
959}
960
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700961int VolumeManager::reset() {
962 // Tear down all existing disks/volumes and start from a blank slate so
963 // newly connected framework hears all events.
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900964
965 // Destroy StubVolume disks. This needs to be done before destroying
966 // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
967 // directory (which is in a StubVolume) is bind-mounted to
968 // /data/media/0/Download.
969 // We do not recreate StubVolumes here because they are managed from outside
970 // Android (e.g. from ChromeOS) and their disk recreation on reset events
971 // should be handled from outside by calling createStubVolume() again.
972 for (const auto& disk : mDisks) {
973 if (disk->isStub()) {
974 disk->destroy();
975 }
976 }
977 // Remove StubVolume from both mDisks and mPendingDisks.
978 const auto isStub = [](const auto& disk) { return disk->isStub(); };
979 mDisks.remove_if(isStub);
980 mPendingDisks.remove_if(isStub);
981
Zima438b242019-09-25 14:37:38 +0100982 for (const auto& vol : mInternalEmulatedVolumes) {
983 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800984 }
Zima438b242019-09-25 14:37:38 +0100985 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100986
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900987 // Destroy and recreate non-StubVolume disks.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700988 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700989 disk->destroy();
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900990 disk->create();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700991 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900992
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600993 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700994 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800995 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +0000996 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +0100997
998 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
999 // with FUSE fds open.
1000 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001001 return 0;
1002}
1003
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001004// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001005int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +01001006 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001007 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001008 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001009 android::vold::sSleepOnUnmount = false;
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001010 // Destroy StubVolume disks before destroying EmulatedVolumes (see the
1011 // comment in VolumeManager::reset()).
1012 for (const auto& disk : mDisks) {
1013 if (disk->isStub()) {
1014 disk->destroy();
1015 }
1016 }
Zima438b242019-09-25 14:37:38 +01001017 for (const auto& vol : mInternalEmulatedVolumes) {
1018 vol->destroy();
1019 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001020 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001021 if (!disk->isStub()) {
1022 disk->destroy();
1023 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001024 }
Zima438b242019-09-25 14:37:38 +01001025
1026 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001027 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001028 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001029 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +02001030
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001031 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001032}
1033
Jeff Sharkey9c484982015-03-31 10:35:33 -07001034int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001035 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001036 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001037
Jeff Sharkey9c484982015-03-31 10:35:33 -07001038 // First, try gracefully unmounting all known devices
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001039 // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
1040 // comment in VolumeManager::reset()).
1041 for (const auto& disk : mDisks) {
1042 if (disk->isStub()) {
1043 disk->unmountAll();
1044 }
1045 }
Zima438b242019-09-25 14:37:38 +01001046 for (const auto& vol : mInternalEmulatedVolumes) {
1047 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -07001048 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001049 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001050 if (!disk->isStub()) {
1051 disk->unmountAll();
1052 }
Jeff Sharkey9c484982015-03-31 10:35:33 -07001053 }
1054
1055 // Worst case we might have some stale mounts lurking around, so
1056 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001057 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001058 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001059 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001060 return -errno;
1061 }
1062
1063 // Some volumes can be stacked on each other, so force unmount in
1064 // reverse order to give us the best chance of success.
1065 std::list<std::string> toUnmount;
1066 mntent* mentry;
1067 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001068 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001069 if ((StartsWith(test, "/mnt/") &&
1070#ifdef __ANDROID_DEBUGGABLE__
1071 !StartsWith(test, "/mnt/scratch") &&
1072#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +01001073 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Inseob Kim1e0299d2024-09-13 14:02:49 +09001074 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable") &&
1075 !StartsWith(test, "/mnt/vm")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001076 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001077 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001078 }
1079 }
1080 endmntent(fp);
1081
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001082 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001083 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001084 android::vold::ForceUnmount(path);
1085 }
1086
1087 return 0;
1088}
1089
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001090int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001091 int size = paths.size();
1092 for (int i = 0; i < size; i++) {
1093 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1094 true /* skipIfDirExists */);
1095 if (result != OK) {
1096 return result;
1097 }
1098 }
1099 return OK;
1100}
1101
1102int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1103 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001104 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001105 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001106 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001107 return -EINVAL;
1108 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001109
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001110 // Find the volume it belongs to
1111 auto filter_fn = [&](const VolumeBase& vol) {
1112 if (vol.getState() != VolumeBase::State::kMounted) {
1113 // The volume must be mounted
1114 return false;
1115 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001116 if (!vol.isVisibleForWrite()) {
1117 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001118 return false;
1119 }
1120 if (vol.getInternalPath().empty()) {
1121 return false;
1122 }
1123 if (vol.getMountUserId() != USER_UNKNOWN &&
1124 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1125 // The app dir must be created on a volume with the same user-id
1126 return false;
1127 }
1128 if (!path.empty() && StartsWith(path, vol.getPath())) {
1129 return true;
1130 }
1131
1132 return false;
1133 };
1134 auto volume = findVolumeWithFilter(filter_fn);
1135 if (volume == nullptr) {
1136 LOG(ERROR) << "Failed to find mounted volume for " << path;
1137 return -EINVAL;
1138 }
Zimc59d7742020-01-06 21:48:16 +00001139 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1140 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1141 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1142 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001143 const std::string lowerPath =
1144 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001145
Martijn Coenen62a4b272020-01-31 15:23:09 +01001146 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1147
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001148 const int access_result = access(lowerPath.c_str(), F_OK);
1149 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001150 // Nothing to fixup
1151 return OK;
1152 }
1153
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001154 if (skipIfDirExists && access_result == 0) {
1155 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1156 // which the dir doesn't need to have correct permission for now yet.
1157 return OK;
1158 }
1159
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001160 if (volume->getType() == VolumeBase::Type::kPublic) {
1161 // On public volumes, we don't need to setup permissions, as everything goes through
1162 // FUSE; just create the dirs and be done with it.
1163 return fs_mkdirs(lowerPath.c_str(), 0700);
1164 }
1165
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001166 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001167 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1168}
1169
1170int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001171 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001172 //sdcardfs magically does this for us
1173 return OK;
1174 }
1175 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001176}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001177
Eric Biggers7e79a432022-03-01 21:19:18 +00001178int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1179 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001180 int id = mNextObbId++;
1181
Martijn Coenend6a612a2020-11-19 10:49:45 +01001182 std::string lowerSourcePath;
1183
1184 // Convert to lower filesystem path
1185 if (StartsWith(sourcePath, "/storage/")) {
1186 auto filter_fn = [&](const VolumeBase& vol) {
1187 if (vol.getState() != VolumeBase::State::kMounted) {
1188 // The volume must be mounted
1189 return false;
1190 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001191 if (!vol.isVisibleForWrite()) {
1192 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001193 return false;
1194 }
1195 if (vol.getInternalPath().empty()) {
1196 return false;
1197 }
1198 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1199 return true;
1200 }
1201
1202 return false;
1203 };
1204 auto volume = findVolumeWithFilter(filter_fn);
1205 if (volume == nullptr) {
1206 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1207 return -EINVAL;
1208 } else {
1209 lowerSourcePath =
1210 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1211 }
1212 } else {
1213 lowerSourcePath = sourcePath;
1214 }
1215
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001216 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001217 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001218 vol->create();
1219
1220 mObbVolumes.push_back(vol);
1221 *outVolId = vol->getId();
1222 return android::OK;
1223}
1224
1225int VolumeManager::destroyObb(const std::string& volId) {
1226 auto i = mObbVolumes.begin();
1227 while (i != mObbVolumes.end()) {
1228 if ((*i)->getId() == volId) {
1229 (*i)->destroy();
1230 i = mObbVolumes.erase(i);
1231 } else {
1232 ++i;
1233 }
1234 }
1235 return android::OK;
1236}
1237
Risan8c9f3322018-10-29 08:52:56 +09001238int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1239 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001240 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001241 std::string* outVolId) {
1242 dev_t stubId = --mNextStubId;
1243 auto vol = std::shared_ptr<android::vold::StubVolume>(
1244 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001245
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001246 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001247 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1248 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001249 if (flags & android::vold::Disk::Flags::kStubVisible) {
1250 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1251 } else {
1252 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1253 }
Risan82e90de2020-02-04 16:07:21 +09001254 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001255 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001256 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001257 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001258 disk->initializePartition(vol);
1259 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001260 *outVolId = vol->getId();
1261 return android::OK;
1262}
1263
1264int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001265 auto tokens = android::base::Split(volId, ":");
1266 CHECK(tokens.size() == 2);
1267 dev_t stubId;
1268 CHECK(android::base::ParseUint(tokens[1], &stubId));
1269 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001270 return android::OK;
1271}
1272
Risan8f6198d2018-10-26 20:56:45 -06001273int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001274 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001275}
1276
Risan8f6198d2018-10-26 20:56:45 -06001277int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001278 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001279}
1280
1281int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001282 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001283}
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001284
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001285static android::status_t getDeviceSize(std::string& device, int64_t* storageSize,
1286 bool isF2fsPrimary) {
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001287 // Follow any symbolic links
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001288 std::string dataDevice;
Daeho Jeong3da20f42024-11-13 13:25:16 -08001289 if (!android::base::Realpath(device, &dataDevice)) {
1290 dataDevice = device;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001291 }
1292
1293 // Handle mapped volumes.
1294 auto& dm = android::dm::DeviceMapper::Instance();
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001295 std::string dmPath = dataDevice;
1296 if (dm.IsDmBlockDevice(dataDevice)) {
1297 for (;;) {
1298 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1299 if (!parent.has_value()) break;
1300 dataDevice = *parent;
1301 }
1302 } else if (isF2fsPrimary) {
1303 if (!dm.GetDmDevicePathByName(android::base::Basename(device), &dmPath)) {
1304 LOG(WARNING) << "No proper dm device for " << device;
1305 isF2fsPrimary = false;
1306 }
1307 }
1308
1309 // Find a device name for F2FS primary partition
1310 std::string f2fsReservedBlocksSysfs;
1311 std::size_t leaf;
1312 if (isF2fsPrimary) {
1313 leaf = dmPath.rfind('/');
1314 if (leaf == std::string::npos) {
1315 LOG(WARNING) << "dm device " << dmPath << " is not a path";
1316 isF2fsPrimary = false;
1317 }
1318 f2fsReservedBlocksSysfs =
1319 std::string() + "/sys/fs/f2fs/" + dmPath.substr(leaf + 1) + "/reserved_blocks";
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001320 }
1321
1322 // Get the potential /sys/block entry
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001323 leaf = dataDevice.rfind('/');
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001324 if (leaf == std::string::npos) {
1325 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1326 return EINVAL;
1327 }
1328 if (dataDevice.substr(0, leaf) != "/dev/block") {
1329 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1330 return EINVAL;
1331 }
1332 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1333
1334 // Look for a directory in /sys/block containing size where the name is a shortened
1335 // version of the name we now have
1336 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1337 // Note that this directory only contains actual disks, not partitions, so this is
1338 // not going to find anything other than the disks
1339 std::string size;
1340 std::string sizeFile;
1341 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1342 if (sysfsDir.back() == '/') {
1343 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1344 return EINVAL;
1345 }
1346 sizeFile = sysfsDir + "/size";
1347 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1348 break;
1349 }
1350 }
1351
1352 // Read the size file and be done
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001353 int64_t sizeNum;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001354 std::stringstream ssSize(size);
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001355 ssSize >> sizeNum;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001356 if (ssSize.fail()) {
1357 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1358 return EINVAL;
1359 }
1360
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001361 sizeNum *= 512;
1362 if (isF2fsPrimary) {
1363 int64_t reservedBlocksNum = 0;
1364 if (!android::base::ReadFileToString(f2fsReservedBlocksSysfs, &size, true)) {
1365 LOG(WARNING) << "Could not find valid entry from " << f2fsReservedBlocksSysfs;
1366 } else {
1367 std::stringstream reservedBlocks(size);
1368 reservedBlocks >> reservedBlocksNum;
1369 if (reservedBlocks.fail()) {
1370 LOG(WARNING) << f2fsReservedBlocksSysfs << " cannot be read as an integer";
1371 reservedBlocksNum = 0;
1372 }
1373 }
1374 int64_t blockSize = android::base::GetIntProperty("ro.boot.hardware.cpu.pagesize", 0);
1375 sizeNum -= reservedBlocksNum * blockSize;
1376 }
1377
1378 *storageSize = sizeNum;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001379 return OK;
Christopher Ferris71aafb12024-08-04 03:38:29 +00001380}
Daeho Jeong3da20f42024-11-13 13:25:16 -08001381
1382android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1383 android::status_t status;
1384 // Start with the /data mount point from fs_mgr
1385 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1386 if (entry == nullptr) {
1387 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1388 return EINVAL;
1389 }
1390
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001391 status = getDeviceSize(entry->blk_device, storageSize, entry->fs_type == "f2fs");
Daeho Jeong3da20f42024-11-13 13:25:16 -08001392 if (status != OK) {
1393 return status;
1394 }
1395
1396 for (auto device : entry->user_devices) {
1397 int64_t deviceStorageSize;
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001398 status = getDeviceSize(device, &deviceStorageSize, false);
Daeho Jeong3da20f42024-11-13 13:25:16 -08001399 if (status != OK) {
1400 return status;
1401 }
1402 *storageSize += deviceStorageSize;
1403 }
1404
1405 return OK;
1406}