blob: fa2b699e0ec1fa572bbf6605f52251abb57fd462 [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;
maxwen3f4bf672020-09-08 16:37:52 +020076using android::base::GetProperty;
Sudheer Shanka53947a32018-08-01 10:24:13 -070077using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070078using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070079using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070080using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060081using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080082using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000083using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080084using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080085using android::vold::DeleteDirContentsAndDir;
Ricky Wai07e64a42020-02-11 14:31:24 +000086using android::vold::EnsureDirExists;
Martijn Coenen73e30102022-07-12 08:11:02 +000087using android::vold::GetFuseMountPathForUser;
Martijn Coenen62a4b272020-01-31 15:23:09 +010088using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070089using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070090using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010091using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010092using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010093using android::vold::PrivateVolume;
himanshuz0ad08622023-07-27 21:15:00 +000094using android::vold::PublicVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080095using android::vold::Symlink;
96using android::vold::Unlink;
97using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080098using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010099using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700100
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600101static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
102
103static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
104
105/* 512MiB is large enough for testing purposes */
106static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700107
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700108static const unsigned int kMajorBlockMmc = 179;
109
Ricky Wai07e64a42020-02-11 14:31:24 +0000110using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
111
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700112VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700113
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700114VolumeManager* VolumeManager::Instance() {
115 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700116 return sInstance;
117}
118
119VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800120 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600121 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900122 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700123 // For security reasons, assume that a secure keyguard is
124 // showing until we hear otherwise
125 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700126}
127
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700128VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800129
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600130int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600131 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700132 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600133 if (access(kPathVirtualDisk, F_OK) != 0) {
134 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
135 }
136
137 if (mVirtualDisk == nullptr) {
138 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
139 LOG(ERROR) << "Failed to create virtual disk";
140 return -1;
141 }
142
143 struct stat buf;
144 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
145 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
146 return -1;
147 }
148
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700149 auto disk = new android::vold::Disk(
150 "virtual", buf.st_rdev, "virtual",
151 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600152 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700153 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600154 }
155 } else {
156 if (mVirtualDisk != nullptr) {
157 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700158 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600159
160 Loop::destroyByDevice(mVirtualDiskPath.c_str());
161 mVirtualDisk = nullptr;
162 }
163
164 if (access(kPathVirtualDisk, F_OK) == 0) {
165 unlink(kPathVirtualDisk);
166 }
167 }
168 return 0;
169}
170
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700171int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800172 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700173 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800174}
175
San Mehatf1b736b2009-10-10 17:22:08 -0700176int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600177 ATRACE_NAME("VolumeManager::start");
178
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700179 // Always start from a clean slate by unmounting everything in
180 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700181 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700182
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600183 Loop::destroyAll();
184
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700185 // Assume that we always have an emulated volume on internal
186 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100187 CHECK(mInternalEmulatedVolumes.empty());
188
189 auto vol = std::shared_ptr<android::vold::VolumeBase>(
190 new android::vold::EmulatedVolume("/data/media", 0));
191 vol->setMountUserId(0);
192 vol->create();
193 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600195 // Consider creating a virtual disk
196 updateVirtualDisk();
197
San Mehatf1b736b2009-10-10 17:22:08 -0700198 return 0;
199}
200
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700201void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700202 std::lock_guard<std::mutex> lock(mLock);
203
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700204 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700205 LOG(DEBUG) << "----------------";
206 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700207 evt->dump();
208 }
San Mehatf1b736b2009-10-10 17:22:08 -0700209
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700210 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
211 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
maxwen3f4bf672020-09-08 16:37:52 +0200212 std::string devName(evt->findParam("DEVNAME") ? evt->findParam("DEVNAME") : "");
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
maxwen3f4bf672020-09-08 16:37:52 +0200234 if (GetBoolProperty("sys.vendor.vold.skip_root_mnt", false)) {
235 // dont add this device as voldmanaged
236 std::string rootDev = GetProperty("dev.mnt.blk.root", "");
237 if (!rootDev.empty()) {
238 if (rootDev.find(devName) != std::string::npos) {
239 LOG(INFO) << "VolumeManager: skip dev = " << devName << " it is the boot device";
240 break;
241 }
242 }
243 }
244
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700245 auto disk =
246 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
247 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
248 break;
249 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700250 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700251 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700252 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700253 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100254 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700255 handleDiskChanged(device);
256 break;
257 }
258 case NetlinkEvent::Action::kRemove: {
259 handleDiskRemoved(device);
260 break;
261 }
262 default: {
263 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
264 break;
265 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700266 }
267}
268
Jeff Sharkey401b2602017-12-14 22:15:20 -0700269void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
270 // For security reasons, if secure keyguard is showing, wait
271 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100272 // Additionally, wait until user 0 is actually started, since we need
273 // the user to be up before we can mount a FUSE daemon to handle the disk.
274 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700275 if (mSecureKeyguardShowing) {
276 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700277 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700278 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100279 } else if (!userZeroStarted) {
280 LOG(INFO) << "Found disk at " << disk->getEventPath()
281 << " but delaying scan due to user zero not having started";
282 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700283 } else {
284 disk->create();
285 mDisks.push_back(disk);
286 }
287}
288
289void VolumeManager::handleDiskChanged(dev_t device) {
290 for (const auto& disk : mDisks) {
291 if (disk->getDevice() == device) {
292 disk->readMetadata();
293 disk->readPartitions();
294 }
295 }
296
297 // For security reasons, we ignore all pending disks, since
298 // we'll scan them once the device is unlocked
299}
300
301void VolumeManager::handleDiskRemoved(dev_t device) {
302 auto i = mDisks.begin();
303 while (i != mDisks.end()) {
304 if ((*i)->getDevice() == device) {
305 (*i)->destroy();
306 i = mDisks.erase(i);
307 } else {
308 ++i;
309 }
310 }
311 auto j = mPendingDisks.begin();
312 while (j != mPendingDisks.end()) {
313 if ((*j)->getDevice() == device) {
314 j = mPendingDisks.erase(j);
315 } else {
316 ++j;
317 }
318 }
319}
320
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800322 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700323 mDiskSources.push_back(diskSource);
324}
325
326std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
327 for (auto disk : mDisks) {
328 if (disk->getId() == id) {
329 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700330 }
331 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700332 return nullptr;
333}
San Mehatf1b736b2009-10-10 17:22:08 -0700334
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700335std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100336 for (const auto& vol : mInternalEmulatedVolumes) {
337 if (vol->getId() == id) {
338 return vol;
339 }
San Mehatf1b736b2009-10-10 17:22:08 -0700340 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700341 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700342 auto vol = disk->findVolume(id);
343 if (vol != nullptr) {
344 return vol;
345 }
346 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600347 for (const auto& vol : mObbVolumes) {
348 if (vol->getId() == id) {
349 return vol;
350 }
351 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700352 return nullptr;
353}
354
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800355void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
356 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700357 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700358 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700359 disk->listVolumes(type, list);
360 }
361}
362
Eric Biggers78627292023-08-01 22:36:55 +0000363bool VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700364 std::string normalizedGuid;
365 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
366 LOG(WARNING) << "Invalid GUID " << partGuid;
Eric Biggers78627292023-08-01 22:36:55 +0000367 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700368 }
369
370 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
371 if (unlink(keyPath.c_str()) != 0) {
372 LOG(ERROR) << "Failed to unlink " << keyPath;
Eric Biggers78627292023-08-01 22:36:55 +0000373 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700374 }
Eric Biggers78627292023-08-01 22:36:55 +0000375 return true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700376}
377
Zima438b242019-09-25 14:37:38 +0100378void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
379 // Destroy and remove all unstacked EmulatedVolumes for the user
380 auto i = mInternalEmulatedVolumes.begin();
381 while (i != mInternalEmulatedVolumes.end()) {
382 auto vol = *i;
383 if (vol->getMountUserId() == userId) {
384 vol->destroy();
385 i = mInternalEmulatedVolumes.erase(i);
386 } else {
387 i++;
388 }
389 }
390
391 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
392 std::list<std::string> private_vols;
393 listVolumes(VolumeBase::Type::kPrivate, private_vols);
394 for (const std::string& id : private_vols) {
395 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
396 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
397 if (pvol->getState() == VolumeBase::State::kMounted) {
398 for (const auto& vol : pvol->getVolumes()) {
399 if (vol->getMountUserId() == userId) {
400 vols_to_remove.push_back(vol);
401 }
402 }
403 for (const auto& vol : vols_to_remove) {
404 vol->destroy();
405 pvol->removeVolume(vol);
406 }
407 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
408 }
409}
410
411void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
412 // Create unstacked EmulatedVolumes for the user
413 auto vol = std::shared_ptr<android::vold::VolumeBase>(
414 new android::vold::EmulatedVolume("/data/media", userId));
415 vol->setMountUserId(userId);
416 mInternalEmulatedVolumes.push_back(vol);
417 vol->create();
418
419 // Create stacked EmulatedVolumes for the user on each PrivateVolume
420 std::list<std::string> private_vols;
421 listVolumes(VolumeBase::Type::kPrivate, private_vols);
422 for (const std::string& id : private_vols) {
423 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
424 if (pvol->getState() == VolumeBase::State::kMounted) {
425 auto evol =
426 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
427 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
428 userId));
429 evol->setMountUserId(userId);
430 pvol->addVolume(evol);
431 evol->create();
432 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
433 }
434}
435
Martijn Coenen73e30102022-07-12 08:11:02 +0000436userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
437 if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
438 return USER_UNKNOWN;
439 }
440 return mSharedStorageUser.at(userId);
441}
442
443int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
444 userid_t sharesStorageWithUserId) {
Zima438b242019-09-25 14:37:38 +0100445 LOG(INFO) << "onUserAdded: " << userId;
446
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700447 mAddedUsers[userId] = userSerialNumber;
Martijn Coenen73e30102022-07-12 08:11:02 +0000448 if (sharesStorageWithUserId != USER_UNKNOWN) {
449 mSharedStorageUser[userId] = sharesStorageWithUserId;
450 }
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700451 return 0;
452}
453
454int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100455 LOG(INFO) << "onUserRemoved: " << userId;
456
Zim2d45d9b2019-11-14 16:19:05 +0000457 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700458 mAddedUsers.erase(userId);
Martijn Coenen73e30102022-07-12 08:11:02 +0000459 mSharedStorageUser.erase(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700460 return 0;
461}
462
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700463int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100464 LOG(INFO) << "onUserStarted: " << userId;
465
Zim2d45d9b2019-11-14 16:19:05 +0000466 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
467 createEmulatedVolumesForUser(userId);
himanshuz0ad08622023-07-27 21:15:00 +0000468 std::list<std::string> public_vols;
469 listVolumes(VolumeBase::Type::kPublic, public_vols);
470 for (const std::string& id : public_vols) {
471 PublicVolume* pvol = static_cast<PublicVolume*>(findVolume(id).get());
472 if (pvol->getState() != VolumeBase::State::kMounted) {
473 continue;
474 }
475 if (pvol->isVisible() == 0) {
476 continue;
477 }
478 userid_t mountUserId = pvol->getMountUserId();
479 if (userId == mountUserId) {
480 // No need to bind mount for the user that owns the mount
481 continue;
482 }
483 if (mountUserId != VolumeManager::Instance()->getSharedStorageUser(userId)) {
484 // No need to bind if the user does not share storage with the mount owner
485 continue;
486 }
Himanshu Gupta4f179692024-05-06 11:40:19 +0100487 // Create mount directory for the user as there is a chance that no other Volume is
488 // mounted for the user (ex: if the user is just started), so /mnt/user/user_id does
489 // not exist yet.
490 auto mountDirStatus = android::vold::PrepareMountDirForUser(userId);
491 if (mountDirStatus != OK) {
492 LOG(ERROR) << "Failed to create Mount Directory for user " << userId;
493 }
himanshuz0ad08622023-07-27 21:15:00 +0000494 auto bindMountStatus = pvol->bindMountForUser(userId);
495 if (bindMountStatus != OK) {
496 LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
497 << "Failed. Error: " << bindMountStatus;
498 }
499 }
Zim2d45d9b2019-11-14 16:19:05 +0000500 }
501
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700502 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100503
504 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700505 return 0;
506}
507
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700508int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700509 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100510
Zim2d45d9b2019-11-14 16:19:05 +0000511 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100512 destroyEmulatedVolumesForUser(userId);
513 }
514
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700515 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700516 return 0;
517}
518
Martijn Coenencf5916f2020-01-03 14:36:45 +0100519void VolumeManager::createPendingDisksIfNeeded() {
520 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
521 if (!mSecureKeyguardShowing && userZeroStarted) {
522 // Now that secure keyguard has been dismissed and user 0 has
523 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700524 for (const auto& disk : mPendingDisks) {
525 disk->create();
526 mDisks.push_back(disk);
527 }
528 mPendingDisks.clear();
529 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100530}
531
532int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
533 mSecureKeyguardShowing = isShowing;
534 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700535 return 0;
536}
537
Narayan Kamath02efdf52019-11-27 10:53:51 +0000538// This code is executed after a fork so it's very important that the set of
539// methods we call here is strictly limited.
540//
541// TODO: Get rid of this guesswork altogether and instead exec a process
542// immediately after fork to do our bindding for us.
543static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000544 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000545 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000546 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000547 strerror(errno));
548 return false;
549 }
550
551 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
552 // to also protect against future changes that may cause issues across a
553 // fork.
554 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
555 errno != ENOENT) {
556 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
557 strerror(errno));
558 return false;
559 }
560
561 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
562 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000563 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000564 return false;
565 }
566
567 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
568 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000569 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000570 strerror(errno));
571 return false;
572 }
573
574 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
575 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000576 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000577 return false;
578 }
579
580 return true;
581}
582
Ricky Wai07e64a42020-02-11 14:31:24 +0000583// Fork the process and remount storage
584bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
585 int32_t mountMode = *static_cast<int32_t*>(params);
586 std::string userSource;
587 std::string storageSource;
588 pid_t child;
589 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800590 switch (mountMode) {
591 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000592 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800593 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000594 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800595 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000596 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700597 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000598 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800599 break;
Zim981222f2019-09-09 10:24:44 +0100600 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000601 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800602 default:
603 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000604 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800605 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000606 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700607
Ricky Wai07e64a42020-02-11 14:31:24 +0000608 // Fork a child to mount user-specific symlink helper into place
609 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
610 if (!(child = fork())) {
611 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
612 _exit(0);
613 } else {
614 _exit(1);
615 }
616 }
617
618 if (child == -1) {
619 PLOG(ERROR) << "Failed to fork";
620 return false;
621 } else {
622 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
623 }
624 return true;
625}
626
627// Helper function to scan all processes in /proc and call the callback if:
628// 1). pid belongs to an app process
629// 2). If input uid is 0 or it matches the process uid
630// 3). If userId is not -1 or userId matches the process userId
631bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700632 DIR* dir;
633 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600634 std::string rootName;
635 std::string pidName;
Jooyung Hana9f21712023-08-25 15:38:12 +0900636 std::string exeName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700637 int pidFd;
638 int nsFd;
639 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700640
641 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000642 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
643 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700644 }
645
646 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600647 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000648 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700649 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000650 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700651 }
652
Ricky Wai07e64a42020-02-11 14:31:24 +0000653 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700654 // Poke through all running PIDs look for apps running as UID
655 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700656 pid_t pid;
657 if (de->d_type != DT_DIR) continue;
658 if (!android::base::ParseInt(de->d_name, &pid)) continue;
659
Jeff Sharkey66270a22015-06-24 11:49:24 -0700660 pidFd = -1;
661 nsFd = -1;
662
663 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
664 if (pidFd < 0) {
665 goto next;
666 }
667 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000668 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700669 goto next;
670 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000671 if (uid != 0 && sb.st_uid != uid) {
672 goto next;
673 }
674 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700675 goto next;
676 }
677
678 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600679 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000680 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
681 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700682 goto next;
683 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600684 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700685 goto next;
686 }
687
Jooyung Hana9f21712023-08-25 15:38:12 +0900688 // Some early native processes have mount namespaces that are different
689 // from that of the init. Therefore, above check can't filter them out.
690 // Since the propagation type of / is 'shared', unmounting /storage
691 // for the early native processes affects other processes including
692 // init. Filter out such processes by skipping if a process is a
693 // non-Java process whose UID is < AID_APP_START. (The UID condition
694 // is required to not filter out child processes spawned by apps.)
695 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
696 goto next;
697 }
698 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
699 goto next;
Jiyong Park8d21c922019-01-04 13:35:25 +0900700 }
701
Jeff Sharkey66270a22015-06-24 11:49:24 -0700702 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700703 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
704 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700705 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000706 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
707 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700708 goto next;
709 }
710
Ricky Wai07e64a42020-02-11 14:31:24 +0000711 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
712 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700713 }
714
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700715 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700716 close(nsFd);
717 close(pidFd);
718 }
719 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000720 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
721 return true;
722}
723
Ricky Waia2ca11e2021-01-15 14:03:23 +0000724// In each app's namespace, unmount obb and data dirs
725static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
726 int uid, const char* targets[], int size) {
727 // This code is executed after a fork so it's very important that the set of
728 // methods we call here is strictly limited.
729 if (setns(nsFd, CLONE_NEWNS) != 0) {
730 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
731 return false;
732 }
733
734 // Unmount of Android/data/foo needs to be done before Android/data below.
735 bool result = true;
736 for (int i = 0; i < size; i++) {
737 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
738 errno != ENOENT) {
739 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
740 targets[i], strerror(errno));
741 result = false;
742 }
743 }
744
745 // Mount tmpfs on Android/data and Android/obb
746 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
747 errno != ENOENT) {
748 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
749 android_data_dir, strerror(errno));
750 result = false;
751 }
752 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
753 errno != ENOENT) {
754 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
755 android_obb_dir, strerror(errno));
756 result = false;
757 }
758 return result;
759}
760
Ricky Waie96b34f2020-05-07 16:01:33 +0100761// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
762// package dirs.
763static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
764 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000765 // This code is executed after a fork so it's very important that the set of
766 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000767 if (setns(nsFd, CLONE_NEWNS) != 0) {
768 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
769 return false;
770 }
771
Ricky Waie96b34f2020-05-07 16:01:33 +0100772 // Mount tmpfs on Android/data and Android/obb
773 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
774 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
775 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
776 android_data_dir, strerror(errno));
777 return false;
778 }
779 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
780 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
781 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
782 android_obb_dir, strerror(errno));
783 return false;
784 }
785
Ricky Wai6b122572020-02-28 16:30:47 +0000786 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100787 // Create package dir and bind mount it to the actual one.
788 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
789 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
790 targets[i], strerror(errno));
791 return false;
792 }
Ricky Wai6b122572020-02-28 16:30:47 +0000793 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
794 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
795 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000796 return false;
797 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000798 }
799 return true;
800}
801
Ricky Wai6b122572020-02-28 16:30:47 +0000802static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
803 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700804 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000805 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
806 userId, dirName.c_str(), packageName.c_str());
807 } else {
808 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
809 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000810 }
Ricky Wai6b122572020-02-28 16:30:47 +0000811}
812
813static std::string getStorageDirTarget(userid_t userId, std::string dirName,
814 std::string packageName) {
815 return StringPrintf("/storage/emulated/%d/%s/%s",
816 userId, dirName.c_str(), packageName.c_str());
817}
818
Ricky Waia2ca11e2021-01-15 14:03:23 +0000819// Fork the process and remount / unmount app data and obb dirs
820bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000821 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000822 userid_t userId = multiuser_get_user_id(uid);
823 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
824 android::base::unique_fd nsFd(
825 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
826 if (nsFd == -1) {
827 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
828 return false;
829 }
830 // Storing both Android/obb and Android/data paths.
831 int size = packageNames.size() * 2;
832
833 std::unique_ptr<std::string[]> sources(new std::string[size]);
834 std::unique_ptr<std::string[]> targets(new std::string[size]);
835 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
836 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
837 const char** sources_cstr = sources_uptr.get();
838 const char** targets_cstr = targets_uptr.get();
839
840 for (int i = 0; i < size; i += 2) {
841 std::string const& packageName = packageNames[i/2];
842 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
843 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
844 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
845 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
846
847 sources_cstr[i] = sources[i].c_str();
848 targets_cstr[i] = targets[i].c_str();
849 sources_cstr[i+1] = sources[i+1].c_str();
850 targets_cstr[i+1] = targets[i+1].c_str();
851 }
852
853 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000854 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000855 // This needs to be done before EnsureDirExists to ensure Android/ is created.
856 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000857 if (status != OK) {
858 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
859 return false;
860 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000861 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
862 if (status != OK) {
863 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
864 return false;
865 }
Ricky Wai6b122572020-02-28 16:30:47 +0000866 }
867
Ricky Waie96b34f2020-05-07 16:01:33 +0100868 char android_data_dir[PATH_MAX];
869 char android_obb_dir[PATH_MAX];
870 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
871 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
872
Ricky Wai6b122572020-02-28 16:30:47 +0000873 pid_t child;
874 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
875 // original vold process mount namespace.
876 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000877 if (doUnmount) {
878 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
879 targets_cstr, size)) {
880 _exit(0);
881 } else {
882 _exit(1);
883 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000884 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000885 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
886 sources_cstr, targets_cstr, size)) {
887 _exit(0);
888 } else {
889 _exit(1);
890 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000891 }
892 }
Ricky Wai6b122572020-02-28 16:30:47 +0000893
Ricky Wai07e64a42020-02-11 14:31:24 +0000894 if (child == -1) {
895 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000896 return false;
897 } else {
898 int status;
899 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
900 PLOG(ERROR) << "Failed to waitpid: " << child;
901 return false;
902 }
903 if (!WIFEXITED(status)) {
904 PLOG(ERROR) << "Process did not exit normally, status: " << status;
905 return false;
906 }
907 if (WEXITSTATUS(status)) {
908 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
909 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000910 }
911 }
Ricky Wai6b122572020-02-28 16:30:47 +0000912 return true;
913}
914
Ricky Waia2ca11e2021-01-15 14:03:23 +0000915int VolumeManager::handleAppStorageDirs(int uid, int pid,
916 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000917 // Only run the remount if fuse is mounted for that user.
918 userid_t userId = multiuser_get_user_id(uid);
919 bool fuseMounted = false;
920 for (auto& vol : mInternalEmulatedVolumes) {
921 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
922 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
923 if (emulatedVol) {
924 fuseMounted = emulatedVol->isFuseMounted();
925 }
926 break;
927 }
928 }
929 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000930 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000931 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700932 return 0;
933}
934
Martijn Coenen23c04452020-04-29 07:49:41 +0200935int VolumeManager::abortFuse() {
936 return android::vold::AbortFuseConnections();
937}
938
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700939int VolumeManager::reset() {
940 // Tear down all existing disks/volumes and start from a blank slate so
941 // newly connected framework hears all events.
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900942
943 // Destroy StubVolume disks. This needs to be done before destroying
944 // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
945 // directory (which is in a StubVolume) is bind-mounted to
946 // /data/media/0/Download.
947 // We do not recreate StubVolumes here because they are managed from outside
948 // Android (e.g. from ChromeOS) and their disk recreation on reset events
949 // should be handled from outside by calling createStubVolume() again.
950 for (const auto& disk : mDisks) {
951 if (disk->isStub()) {
952 disk->destroy();
953 }
954 }
955 // Remove StubVolume from both mDisks and mPendingDisks.
956 const auto isStub = [](const auto& disk) { return disk->isStub(); };
957 mDisks.remove_if(isStub);
958 mPendingDisks.remove_if(isStub);
959
Zima438b242019-09-25 14:37:38 +0100960 for (const auto& vol : mInternalEmulatedVolumes) {
961 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800962 }
Zima438b242019-09-25 14:37:38 +0100963 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100964
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900965 // Destroy and recreate non-StubVolume disks.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700966 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700967 disk->destroy();
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900968 disk->create();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700969 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900970
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600971 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700972 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800973 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +0000974 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +0100975
976 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
977 // with FUSE fds open.
978 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700979 return 0;
980}
981
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700982// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700983int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100984 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700985 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700986 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700987 android::vold::sSleepOnUnmount = false;
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900988 // Destroy StubVolume disks before destroying EmulatedVolumes (see the
989 // comment in VolumeManager::reset()).
990 for (const auto& disk : mDisks) {
991 if (disk->isStub()) {
992 disk->destroy();
993 }
994 }
Zima438b242019-09-25 14:37:38 +0100995 for (const auto& vol : mInternalEmulatedVolumes) {
996 vol->destroy();
997 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700998 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900999 if (!disk->isStub()) {
1000 disk->destroy();
1001 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001002 }
Zima438b242019-09-25 14:37:38 +01001003
1004 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001005 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001006 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001007 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +02001008
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001009 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001010}
1011
Jeff Sharkey9c484982015-03-31 10:35:33 -07001012int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001013 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001014 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001015
Jeff Sharkey9c484982015-03-31 10:35:33 -07001016 // First, try gracefully unmounting all known devices
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001017 // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
1018 // comment in VolumeManager::reset()).
1019 for (const auto& disk : mDisks) {
1020 if (disk->isStub()) {
1021 disk->unmountAll();
1022 }
1023 }
Zima438b242019-09-25 14:37:38 +01001024 for (const auto& vol : mInternalEmulatedVolumes) {
1025 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -07001026 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001027 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001028 if (!disk->isStub()) {
1029 disk->unmountAll();
1030 }
Jeff Sharkey9c484982015-03-31 10:35:33 -07001031 }
1032
1033 // Worst case we might have some stale mounts lurking around, so
1034 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001035 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001036 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001037 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001038 return -errno;
1039 }
1040
1041 // Some volumes can be stacked on each other, so force unmount in
1042 // reverse order to give us the best chance of success.
1043 std::list<std::string> toUnmount;
1044 mntent* mentry;
1045 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001046 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001047 if ((StartsWith(test, "/mnt/") &&
1048#ifdef __ANDROID_DEBUGGABLE__
1049 !StartsWith(test, "/mnt/scratch") &&
1050#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +01001051 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Inseob Kim1e0299d2024-09-13 14:02:49 +09001052 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable") &&
1053 !StartsWith(test, "/mnt/vm")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001054 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001055 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001056 }
1057 }
1058 endmntent(fp);
1059
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001060 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001061 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001062 android::vold::ForceUnmount(path);
1063 }
1064
1065 return 0;
1066}
1067
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001068int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001069 int size = paths.size();
1070 for (int i = 0; i < size; i++) {
1071 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1072 true /* skipIfDirExists */);
1073 if (result != OK) {
1074 return result;
1075 }
1076 }
1077 return OK;
1078}
1079
1080int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1081 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001082 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001083 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001084 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001085 return -EINVAL;
1086 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001087
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001088 // Find the volume it belongs to
1089 auto filter_fn = [&](const VolumeBase& vol) {
1090 if (vol.getState() != VolumeBase::State::kMounted) {
1091 // The volume must be mounted
1092 return false;
1093 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001094 if (!vol.isVisibleForWrite()) {
1095 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001096 return false;
1097 }
1098 if (vol.getInternalPath().empty()) {
1099 return false;
1100 }
1101 if (vol.getMountUserId() != USER_UNKNOWN &&
1102 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1103 // The app dir must be created on a volume with the same user-id
1104 return false;
1105 }
1106 if (!path.empty() && StartsWith(path, vol.getPath())) {
1107 return true;
1108 }
1109
1110 return false;
1111 };
1112 auto volume = findVolumeWithFilter(filter_fn);
1113 if (volume == nullptr) {
1114 LOG(ERROR) << "Failed to find mounted volume for " << path;
1115 return -EINVAL;
1116 }
Zimc59d7742020-01-06 21:48:16 +00001117 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1118 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1119 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1120 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001121 const std::string lowerPath =
1122 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001123
Martijn Coenen62a4b272020-01-31 15:23:09 +01001124 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1125
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001126 const int access_result = access(lowerPath.c_str(), F_OK);
1127 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001128 // Nothing to fixup
1129 return OK;
1130 }
1131
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001132 if (skipIfDirExists && access_result == 0) {
1133 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1134 // which the dir doesn't need to have correct permission for now yet.
1135 return OK;
1136 }
1137
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001138 if (volume->getType() == VolumeBase::Type::kPublic) {
1139 // On public volumes, we don't need to setup permissions, as everything goes through
1140 // FUSE; just create the dirs and be done with it.
1141 return fs_mkdirs(lowerPath.c_str(), 0700);
1142 }
1143
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001144 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001145 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1146}
1147
1148int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001149 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001150 //sdcardfs magically does this for us
1151 return OK;
1152 }
1153 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001154}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001155
Eric Biggers7e79a432022-03-01 21:19:18 +00001156int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1157 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001158 int id = mNextObbId++;
1159
Martijn Coenend6a612a2020-11-19 10:49:45 +01001160 std::string lowerSourcePath;
1161
1162 // Convert to lower filesystem path
1163 if (StartsWith(sourcePath, "/storage/")) {
1164 auto filter_fn = [&](const VolumeBase& vol) {
1165 if (vol.getState() != VolumeBase::State::kMounted) {
1166 // The volume must be mounted
1167 return false;
1168 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001169 if (!vol.isVisibleForWrite()) {
1170 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001171 return false;
1172 }
1173 if (vol.getInternalPath().empty()) {
1174 return false;
1175 }
1176 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1177 return true;
1178 }
1179
1180 return false;
1181 };
1182 auto volume = findVolumeWithFilter(filter_fn);
1183 if (volume == nullptr) {
1184 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1185 return -EINVAL;
1186 } else {
1187 lowerSourcePath =
1188 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1189 }
1190 } else {
1191 lowerSourcePath = sourcePath;
1192 }
1193
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001194 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001195 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001196 vol->create();
1197
1198 mObbVolumes.push_back(vol);
1199 *outVolId = vol->getId();
1200 return android::OK;
1201}
1202
1203int VolumeManager::destroyObb(const std::string& volId) {
1204 auto i = mObbVolumes.begin();
1205 while (i != mObbVolumes.end()) {
1206 if ((*i)->getId() == volId) {
1207 (*i)->destroy();
1208 i = mObbVolumes.erase(i);
1209 } else {
1210 ++i;
1211 }
1212 }
1213 return android::OK;
1214}
1215
Risan8c9f3322018-10-29 08:52:56 +09001216int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1217 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001218 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001219 std::string* outVolId) {
1220 dev_t stubId = --mNextStubId;
1221 auto vol = std::shared_ptr<android::vold::StubVolume>(
1222 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001223
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001224 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001225 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1226 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001227 if (flags & android::vold::Disk::Flags::kStubVisible) {
1228 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1229 } else {
1230 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1231 }
Risan82e90de2020-02-04 16:07:21 +09001232 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001233 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001234 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001235 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001236 disk->initializePartition(vol);
1237 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001238 *outVolId = vol->getId();
1239 return android::OK;
1240}
1241
1242int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001243 auto tokens = android::base::Split(volId, ":");
1244 CHECK(tokens.size() == 2);
1245 dev_t stubId;
1246 CHECK(android::base::ParseUint(tokens[1], &stubId));
1247 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001248 return android::OK;
1249}
1250
Risan8f6198d2018-10-26 20:56:45 -06001251int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001252 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001253}
1254
Risan8f6198d2018-10-26 20:56:45 -06001255int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001256 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001257}
1258
1259int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001260 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001261}
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001262
Daeho Jeong3da20f42024-11-13 13:25:16 -08001263static android::status_t getDeviceSize(std::string& device, int64_t* storageSize) {
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001264 // Follow any symbolic links
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001265 std::string dataDevice;
Daeho Jeong3da20f42024-11-13 13:25:16 -08001266 if (!android::base::Realpath(device, &dataDevice)) {
1267 dataDevice = device;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001268 }
1269
1270 // Handle mapped volumes.
1271 auto& dm = android::dm::DeviceMapper::Instance();
1272 for (;;) {
1273 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1274 if (!parent.has_value()) break;
1275 dataDevice = *parent;
1276 }
1277
1278 // Get the potential /sys/block entry
1279 std::size_t leaf = dataDevice.rfind('/');
1280 if (leaf == std::string::npos) {
1281 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1282 return EINVAL;
1283 }
1284 if (dataDevice.substr(0, leaf) != "/dev/block") {
1285 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1286 return EINVAL;
1287 }
1288 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1289
1290 // Look for a directory in /sys/block containing size where the name is a shortened
1291 // version of the name we now have
1292 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1293 // Note that this directory only contains actual disks, not partitions, so this is
1294 // not going to find anything other than the disks
1295 std::string size;
1296 std::string sizeFile;
1297 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1298 if (sysfsDir.back() == '/') {
1299 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1300 return EINVAL;
1301 }
1302 sizeFile = sysfsDir + "/size";
1303 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1304 break;
1305 }
1306 }
1307
1308 // Read the size file and be done
1309 std::stringstream ssSize(size);
1310 ssSize >> *storageSize;
1311 if (ssSize.fail()) {
1312 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1313 return EINVAL;
1314 }
1315
1316 *storageSize *= 512;
1317 return OK;
Christopher Ferris71aafb12024-08-04 03:38:29 +00001318}
Daeho Jeong3da20f42024-11-13 13:25:16 -08001319
1320android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1321 android::status_t status;
1322 // Start with the /data mount point from fs_mgr
1323 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1324 if (entry == nullptr) {
1325 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1326 return EINVAL;
1327 }
1328
1329 status = getDeviceSize(entry->blk_device, storageSize);
1330 if (status != OK) {
1331 return status;
1332 }
1333
1334 for (auto device : entry->user_devices) {
1335 int64_t deviceStorageSize;
1336 status = getDeviceSize(device, &deviceStorageSize);
1337 if (status != OK) {
1338 return status;
1339 }
1340 *storageSize += deviceStorageSize;
1341 }
1342
1343 return OK;
1344}