blob: 4af7ff0a54be9f92b0a6450cd99ef915df5259a6 [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);
Omar Eissad9c4b232025-03-13 11:52:43 +0000468
469 userid_t sharedStorageUserId = VolumeManager::Instance()->getSharedStorageUser(userId);
470 if (sharedStorageUserId != USER_UNKNOWN) {
471 std::list<std::string> public_vols;
472 listVolumes(VolumeBase::Type::kPublic, public_vols);
473 for (const std::string& id : public_vols) {
474 PublicVolume *pvol = static_cast<PublicVolume *>(findVolume(id).get());
475 if (pvol->getState() != VolumeBase::State::kMounted) {
476 continue;
477 }
478 if (pvol->isVisible() == 0) {
479 continue;
480 }
481 userid_t mountUserId = pvol->getMountUserId();
482 if (userId == mountUserId) {
483 // No need to bind mount for the user that owns the mount
484 continue;
485 }
486
487 if (mountUserId != sharedStorageUserId) {
488 // No need to bind if the user does not share storage with the mount owner
489 continue;
490 }
491 // Create mount directory for the user as there is a chance that no other Volume is
492 // mounted for the user (ex: if the user is just started),
493 // so /mnt/user/user_id does not exist yet.
494 auto mountDirStatus = android::vold::PrepareMountDirForUser(userId);
495 if (mountDirStatus != OK) {
496 LOG(ERROR) << "Failed to create Mount Directory for user " << userId;
497 }
498 auto bindMountStatus = pvol->bindMountForUser(userId);
499 if (bindMountStatus != OK) {
500 LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
501 << "Failed. Error: " << bindMountStatus;
502 }
himanshuz0ad08622023-07-27 21:15:00 +0000503 }
504 }
Zim2d45d9b2019-11-14 16:19:05 +0000505 }
506
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700507 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100508
509 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700510 return 0;
511}
512
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700513int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700514 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100515
Zim2d45d9b2019-11-14 16:19:05 +0000516 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100517 destroyEmulatedVolumesForUser(userId);
Omar Eissad9c4b232025-03-13 11:52:43 +0000518
519 userid_t sharedStorageUserId = VolumeManager::Instance()->getSharedStorageUser(userId);
520 if (sharedStorageUserId != USER_UNKNOWN) {
521 std::list<std::string> public_vols;
522 listVolumes(VolumeBase::Type::kPublic, public_vols);
523 for (const std::string &id: public_vols) {
524 PublicVolume *pvol = static_cast<PublicVolume *>(findVolume(id).get());
525 if (pvol->getState() != VolumeBase::State::kMounted) {
526 continue;
527 }
528 if (pvol->isVisible() == 0) {
529 continue;
530 }
531 userid_t mountUserId = pvol->getMountUserId();
532 if (userId == mountUserId) {
533 // No need to remove bind mount for the user that owns the mount
534 continue;
535 }
536 if (mountUserId != sharedStorageUserId) {
537 // No need to remove bind mount
538 // if the user does not share storage with the mount owner
539 continue;
540 }
541 LOG(INFO) << "Removing Public Volume Bind Mount for: " << userId;
542 auto mountPath = GetFuseMountPathForUser(userId, pvol->getStableName());
543 android::vold::ForceUnmount(mountPath);
544 rmdir(mountPath.c_str());
545 }
546 }
547
Zima438b242019-09-25 14:37:38 +0100548 }
549
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700550 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700551 return 0;
552}
553
Martijn Coenencf5916f2020-01-03 14:36:45 +0100554void VolumeManager::createPendingDisksIfNeeded() {
555 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
556 if (!mSecureKeyguardShowing && userZeroStarted) {
557 // Now that secure keyguard has been dismissed and user 0 has
558 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700559 for (const auto& disk : mPendingDisks) {
560 disk->create();
561 mDisks.push_back(disk);
562 }
563 mPendingDisks.clear();
564 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100565}
566
567int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
568 mSecureKeyguardShowing = isShowing;
569 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700570 return 0;
571}
572
Narayan Kamath02efdf52019-11-27 10:53:51 +0000573// This code is executed after a fork so it's very important that the set of
574// methods we call here is strictly limited.
575//
576// TODO: Get rid of this guesswork altogether and instead exec a process
577// immediately after fork to do our bindding for us.
578static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000579 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000580 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000581 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000582 strerror(errno));
583 return false;
584 }
585
586 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
587 // to also protect against future changes that may cause issues across a
588 // fork.
589 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
590 errno != ENOENT) {
591 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
592 strerror(errno));
593 return false;
594 }
595
596 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, 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 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000599 return false;
600 }
601
602 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
603 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000604 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000605 strerror(errno));
606 return false;
607 }
608
609 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
610 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000611 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000612 return false;
613 }
614
615 return true;
616}
617
Ricky Wai07e64a42020-02-11 14:31:24 +0000618// Fork the process and remount storage
619bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
620 int32_t mountMode = *static_cast<int32_t*>(params);
621 std::string userSource;
622 std::string storageSource;
623 pid_t child;
624 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800625 switch (mountMode) {
626 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000627 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800628 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000629 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800630 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000631 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700632 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000633 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800634 break;
Zim981222f2019-09-09 10:24:44 +0100635 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000636 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800637 default:
638 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000639 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800640 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000641 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700642
Ricky Wai07e64a42020-02-11 14:31:24 +0000643 // Fork a child to mount user-specific symlink helper into place
644 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
645 if (!(child = fork())) {
646 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
647 _exit(0);
648 } else {
649 _exit(1);
650 }
651 }
652
653 if (child == -1) {
654 PLOG(ERROR) << "Failed to fork";
655 return false;
656 } else {
657 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
658 }
659 return true;
660}
661
662// Helper function to scan all processes in /proc and call the callback if:
663// 1). pid belongs to an app process
664// 2). If input uid is 0 or it matches the process uid
665// 3). If userId is not -1 or userId matches the process userId
666bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700667 DIR* dir;
668 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600669 std::string rootName;
670 std::string pidName;
Jooyung Hana9f21712023-08-25 15:38:12 +0900671 std::string exeName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700672 int pidFd;
673 int nsFd;
674 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700675
676 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000677 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
678 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700679 }
680
681 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600682 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000683 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700684 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000685 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700686 }
687
Ricky Wai07e64a42020-02-11 14:31:24 +0000688 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700689 // Poke through all running PIDs look for apps running as UID
690 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700691 pid_t pid;
692 if (de->d_type != DT_DIR) continue;
693 if (!android::base::ParseInt(de->d_name, &pid)) continue;
694
Jeff Sharkey66270a22015-06-24 11:49:24 -0700695 pidFd = -1;
696 nsFd = -1;
697
698 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
699 if (pidFd < 0) {
700 goto next;
701 }
702 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000703 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700704 goto next;
705 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000706 if (uid != 0 && sb.st_uid != uid) {
707 goto next;
708 }
709 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700710 goto next;
711 }
712
713 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600714 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000715 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
716 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700717 goto next;
718 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600719 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700720 goto next;
721 }
722
Jooyung Hana9f21712023-08-25 15:38:12 +0900723 // Some early native processes have mount namespaces that are different
724 // from that of the init. Therefore, above check can't filter them out.
725 // Since the propagation type of / is 'shared', unmounting /storage
726 // for the early native processes affects other processes including
727 // init. Filter out such processes by skipping if a process is a
728 // non-Java process whose UID is < AID_APP_START. (The UID condition
729 // is required to not filter out child processes spawned by apps.)
730 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
731 goto next;
732 }
733 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
734 goto next;
Jiyong Park8d21c922019-01-04 13:35:25 +0900735 }
736
Jeff Sharkey66270a22015-06-24 11:49:24 -0700737 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700738 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
739 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700740 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000741 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
742 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700743 goto next;
744 }
745
Ricky Wai07e64a42020-02-11 14:31:24 +0000746 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
747 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700748 }
749
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700750 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700751 close(nsFd);
752 close(pidFd);
753 }
754 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000755 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
756 return true;
757}
758
Ricky Waia2ca11e2021-01-15 14:03:23 +0000759// In each app's namespace, unmount obb and data dirs
760static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
761 int uid, const char* targets[], int size) {
762 // This code is executed after a fork so it's very important that the set of
763 // methods we call here is strictly limited.
764 if (setns(nsFd, CLONE_NEWNS) != 0) {
765 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
766 return false;
767 }
768
769 // Unmount of Android/data/foo needs to be done before Android/data below.
770 bool result = true;
771 for (int i = 0; i < size; i++) {
772 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
773 errno != ENOENT) {
774 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
775 targets[i], strerror(errno));
776 result = false;
777 }
778 }
779
780 // Mount tmpfs on Android/data and Android/obb
781 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
782 errno != ENOENT) {
783 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
784 android_data_dir, strerror(errno));
785 result = false;
786 }
787 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
788 errno != ENOENT) {
789 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
790 android_obb_dir, strerror(errno));
791 result = false;
792 }
793 return result;
794}
795
Ricky Waie96b34f2020-05-07 16:01:33 +0100796// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
797// package dirs.
798static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
799 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000800 // This code is executed after a fork so it's very important that the set of
801 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000802 if (setns(nsFd, CLONE_NEWNS) != 0) {
803 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
804 return false;
805 }
806
Ricky Waie96b34f2020-05-07 16:01:33 +0100807 // Mount tmpfs on Android/data and Android/obb
808 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
809 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
810 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
811 android_data_dir, strerror(errno));
812 return false;
813 }
814 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
815 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
816 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
817 android_obb_dir, strerror(errno));
818 return false;
819 }
820
Ricky Wai6b122572020-02-28 16:30:47 +0000821 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100822 // Create package dir and bind mount it to the actual one.
823 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
824 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
825 targets[i], strerror(errno));
826 return false;
827 }
Ricky Wai6b122572020-02-28 16:30:47 +0000828 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
829 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
830 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000831 return false;
832 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000833 }
834 return true;
835}
836
Ricky Wai6b122572020-02-28 16:30:47 +0000837static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
838 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700839 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000840 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
841 userId, dirName.c_str(), packageName.c_str());
842 } else {
843 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
844 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000845 }
Ricky Wai6b122572020-02-28 16:30:47 +0000846}
847
848static std::string getStorageDirTarget(userid_t userId, std::string dirName,
849 std::string packageName) {
850 return StringPrintf("/storage/emulated/%d/%s/%s",
851 userId, dirName.c_str(), packageName.c_str());
852}
853
Ricky Waia2ca11e2021-01-15 14:03:23 +0000854// Fork the process and remount / unmount app data and obb dirs
855bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000856 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000857 userid_t userId = multiuser_get_user_id(uid);
858 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
859 android::base::unique_fd nsFd(
860 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
861 if (nsFd == -1) {
862 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
863 return false;
864 }
865 // Storing both Android/obb and Android/data paths.
866 int size = packageNames.size() * 2;
867
868 std::unique_ptr<std::string[]> sources(new std::string[size]);
869 std::unique_ptr<std::string[]> targets(new std::string[size]);
870 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
871 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
872 const char** sources_cstr = sources_uptr.get();
873 const char** targets_cstr = targets_uptr.get();
874
875 for (int i = 0; i < size; i += 2) {
876 std::string const& packageName = packageNames[i/2];
877 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
878 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
879 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
880 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
881
882 sources_cstr[i] = sources[i].c_str();
883 targets_cstr[i] = targets[i].c_str();
884 sources_cstr[i+1] = sources[i+1].c_str();
885 targets_cstr[i+1] = targets[i+1].c_str();
886 }
887
888 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000889 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000890 // This needs to be done before EnsureDirExists to ensure Android/ is created.
891 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000892 if (status != OK) {
893 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
894 return false;
895 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000896 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
897 if (status != OK) {
898 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
899 return false;
900 }
Ricky Wai6b122572020-02-28 16:30:47 +0000901 }
902
Ricky Waie96b34f2020-05-07 16:01:33 +0100903 char android_data_dir[PATH_MAX];
904 char android_obb_dir[PATH_MAX];
905 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
906 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
907
Ricky Wai6b122572020-02-28 16:30:47 +0000908 pid_t child;
909 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
910 // original vold process mount namespace.
911 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000912 if (doUnmount) {
913 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
914 targets_cstr, size)) {
915 _exit(0);
916 } else {
917 _exit(1);
918 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000919 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000920 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
921 sources_cstr, targets_cstr, size)) {
922 _exit(0);
923 } else {
924 _exit(1);
925 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000926 }
927 }
Ricky Wai6b122572020-02-28 16:30:47 +0000928
Ricky Wai07e64a42020-02-11 14:31:24 +0000929 if (child == -1) {
930 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000931 return false;
932 } else {
933 int status;
934 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
935 PLOG(ERROR) << "Failed to waitpid: " << child;
936 return false;
937 }
938 if (!WIFEXITED(status)) {
939 PLOG(ERROR) << "Process did not exit normally, status: " << status;
940 return false;
941 }
942 if (WEXITSTATUS(status)) {
943 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
944 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000945 }
946 }
Ricky Wai6b122572020-02-28 16:30:47 +0000947 return true;
948}
949
Ricky Waia2ca11e2021-01-15 14:03:23 +0000950int VolumeManager::handleAppStorageDirs(int uid, int pid,
951 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000952 // Only run the remount if fuse is mounted for that user.
953 userid_t userId = multiuser_get_user_id(uid);
954 bool fuseMounted = false;
955 for (auto& vol : mInternalEmulatedVolumes) {
956 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
957 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
958 if (emulatedVol) {
959 fuseMounted = emulatedVol->isFuseMounted();
960 }
961 break;
962 }
963 }
964 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000965 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000966 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700967 return 0;
968}
969
Martijn Coenen23c04452020-04-29 07:49:41 +0200970int VolumeManager::abortFuse() {
971 return android::vold::AbortFuseConnections();
972}
973
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700974int VolumeManager::reset() {
975 // Tear down all existing disks/volumes and start from a blank slate so
976 // newly connected framework hears all events.
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900977
978 // Destroy StubVolume disks. This needs to be done before destroying
979 // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
980 // directory (which is in a StubVolume) is bind-mounted to
981 // /data/media/0/Download.
982 // We do not recreate StubVolumes here because they are managed from outside
983 // Android (e.g. from ChromeOS) and their disk recreation on reset events
984 // should be handled from outside by calling createStubVolume() again.
985 for (const auto& disk : mDisks) {
986 if (disk->isStub()) {
987 disk->destroy();
988 }
989 }
990 // Remove StubVolume from both mDisks and mPendingDisks.
991 const auto isStub = [](const auto& disk) { return disk->isStub(); };
992 mDisks.remove_if(isStub);
993 mPendingDisks.remove_if(isStub);
994
Zima438b242019-09-25 14:37:38 +0100995 for (const auto& vol : mInternalEmulatedVolumes) {
996 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800997 }
Zima438b242019-09-25 14:37:38 +0100998 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100999
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001000 // Destroy and recreate non-StubVolume disks.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001001 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001002 disk->destroy();
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001003 disk->create();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001004 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +09001005
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001006 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001007 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -08001008 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +00001009 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +01001010
1011 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
1012 // with FUSE fds open.
1013 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001014 return 0;
1015}
1016
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001017// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001018int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +01001019 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001020 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001021 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001022 android::vold::sSleepOnUnmount = false;
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001023 // Destroy StubVolume disks before destroying EmulatedVolumes (see the
1024 // comment in VolumeManager::reset()).
1025 for (const auto& disk : mDisks) {
1026 if (disk->isStub()) {
1027 disk->destroy();
1028 }
1029 }
Zima438b242019-09-25 14:37:38 +01001030 for (const auto& vol : mInternalEmulatedVolumes) {
1031 vol->destroy();
1032 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001033 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001034 if (!disk->isStub()) {
1035 disk->destroy();
1036 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001037 }
Zima438b242019-09-25 14:37:38 +01001038
1039 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001040 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001041 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001042 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +02001043
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001044 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001045}
1046
Jeff Sharkey9c484982015-03-31 10:35:33 -07001047int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001048 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001049 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001050
Jeff Sharkey9c484982015-03-31 10:35:33 -07001051 // First, try gracefully unmounting all known devices
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001052 // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
1053 // comment in VolumeManager::reset()).
1054 for (const auto& disk : mDisks) {
1055 if (disk->isStub()) {
1056 disk->unmountAll();
1057 }
1058 }
Zima438b242019-09-25 14:37:38 +01001059 for (const auto& vol : mInternalEmulatedVolumes) {
1060 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -07001061 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001062 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001063 if (!disk->isStub()) {
1064 disk->unmountAll();
1065 }
Jeff Sharkey9c484982015-03-31 10:35:33 -07001066 }
1067
1068 // Worst case we might have some stale mounts lurking around, so
1069 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001070 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001071 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001072 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001073 return -errno;
1074 }
1075
1076 // Some volumes can be stacked on each other, so force unmount in
1077 // reverse order to give us the best chance of success.
1078 std::list<std::string> toUnmount;
1079 mntent* mentry;
1080 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001081 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001082 if ((StartsWith(test, "/mnt/") &&
1083#ifdef __ANDROID_DEBUGGABLE__
1084 !StartsWith(test, "/mnt/scratch") &&
1085#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +01001086 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Inseob Kim1e0299d2024-09-13 14:02:49 +09001087 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable") &&
1088 !StartsWith(test, "/mnt/vm")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001089 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001090 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001091 }
1092 }
1093 endmntent(fp);
1094
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001095 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001096 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001097 android::vold::ForceUnmount(path);
1098 }
1099
1100 return 0;
1101}
1102
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001103int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001104 int size = paths.size();
1105 for (int i = 0; i < size; i++) {
1106 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1107 true /* skipIfDirExists */);
1108 if (result != OK) {
1109 return result;
1110 }
1111 }
1112 return OK;
1113}
1114
1115int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1116 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001117 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001118 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001119 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001120 return -EINVAL;
1121 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001122
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001123 // Find the volume it belongs to
1124 auto filter_fn = [&](const VolumeBase& vol) {
1125 if (vol.getState() != VolumeBase::State::kMounted) {
1126 // The volume must be mounted
1127 return false;
1128 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001129 if (!vol.isVisibleForWrite()) {
1130 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001131 return false;
1132 }
1133 if (vol.getInternalPath().empty()) {
1134 return false;
1135 }
1136 if (vol.getMountUserId() != USER_UNKNOWN &&
1137 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1138 // The app dir must be created on a volume with the same user-id
1139 return false;
1140 }
1141 if (!path.empty() && StartsWith(path, vol.getPath())) {
1142 return true;
1143 }
1144
1145 return false;
1146 };
1147 auto volume = findVolumeWithFilter(filter_fn);
1148 if (volume == nullptr) {
1149 LOG(ERROR) << "Failed to find mounted volume for " << path;
1150 return -EINVAL;
1151 }
Zimc59d7742020-01-06 21:48:16 +00001152 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1153 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1154 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1155 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001156 const std::string lowerPath =
1157 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001158
Martijn Coenen62a4b272020-01-31 15:23:09 +01001159 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1160
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001161 const int access_result = access(lowerPath.c_str(), F_OK);
1162 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001163 // Nothing to fixup
1164 return OK;
1165 }
1166
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001167 if (skipIfDirExists && access_result == 0) {
1168 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1169 // which the dir doesn't need to have correct permission for now yet.
1170 return OK;
1171 }
1172
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001173 if (volume->getType() == VolumeBase::Type::kPublic) {
1174 // On public volumes, we don't need to setup permissions, as everything goes through
1175 // FUSE; just create the dirs and be done with it.
1176 return fs_mkdirs(lowerPath.c_str(), 0700);
1177 }
1178
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001179 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001180 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1181}
1182
1183int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001184 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001185 //sdcardfs magically does this for us
1186 return OK;
1187 }
1188 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001189}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001190
Eric Biggers7e79a432022-03-01 21:19:18 +00001191int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1192 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001193 int id = mNextObbId++;
1194
Martijn Coenend6a612a2020-11-19 10:49:45 +01001195 std::string lowerSourcePath;
1196
1197 // Convert to lower filesystem path
1198 if (StartsWith(sourcePath, "/storage/")) {
1199 auto filter_fn = [&](const VolumeBase& vol) {
1200 if (vol.getState() != VolumeBase::State::kMounted) {
1201 // The volume must be mounted
1202 return false;
1203 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001204 if (!vol.isVisibleForWrite()) {
1205 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001206 return false;
1207 }
1208 if (vol.getInternalPath().empty()) {
1209 return false;
1210 }
1211 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1212 return true;
1213 }
1214
1215 return false;
1216 };
1217 auto volume = findVolumeWithFilter(filter_fn);
1218 if (volume == nullptr) {
1219 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1220 return -EINVAL;
1221 } else {
1222 lowerSourcePath =
1223 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1224 }
1225 } else {
1226 lowerSourcePath = sourcePath;
1227 }
1228
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001229 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001230 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001231 vol->create();
1232
1233 mObbVolumes.push_back(vol);
1234 *outVolId = vol->getId();
1235 return android::OK;
1236}
1237
1238int VolumeManager::destroyObb(const std::string& volId) {
1239 auto i = mObbVolumes.begin();
1240 while (i != mObbVolumes.end()) {
1241 if ((*i)->getId() == volId) {
1242 (*i)->destroy();
1243 i = mObbVolumes.erase(i);
1244 } else {
1245 ++i;
1246 }
1247 }
1248 return android::OK;
1249}
1250
Risan8c9f3322018-10-29 08:52:56 +09001251int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1252 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001253 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001254 std::string* outVolId) {
1255 dev_t stubId = --mNextStubId;
1256 auto vol = std::shared_ptr<android::vold::StubVolume>(
1257 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001258
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001259 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001260 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1261 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001262 if (flags & android::vold::Disk::Flags::kStubVisible) {
1263 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1264 } else {
1265 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1266 }
Risan82e90de2020-02-04 16:07:21 +09001267 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001268 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001269 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001270 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001271 disk->initializePartition(vol);
1272 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001273 *outVolId = vol->getId();
1274 return android::OK;
1275}
1276
1277int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001278 auto tokens = android::base::Split(volId, ":");
1279 CHECK(tokens.size() == 2);
1280 dev_t stubId;
1281 CHECK(android::base::ParseUint(tokens[1], &stubId));
1282 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001283 return android::OK;
1284}
1285
Risan8f6198d2018-10-26 20:56:45 -06001286int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001287 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001288}
1289
Risan8f6198d2018-10-26 20:56:45 -06001290int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001291 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001292}
1293
1294int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001295 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001296}
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001297
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001298static android::status_t getDeviceSize(std::string& device, int64_t* storageSize,
1299 bool isF2fsPrimary) {
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001300 // Follow any symbolic links
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001301 std::string dataDevice;
Daeho Jeong3da20f42024-11-13 13:25:16 -08001302 if (!android::base::Realpath(device, &dataDevice)) {
1303 dataDevice = device;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001304 }
1305
1306 // Handle mapped volumes.
1307 auto& dm = android::dm::DeviceMapper::Instance();
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001308 std::string dmPath = dataDevice;
1309 if (dm.IsDmBlockDevice(dataDevice)) {
1310 for (;;) {
1311 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1312 if (!parent.has_value()) break;
1313 dataDevice = *parent;
1314 }
1315 } else if (isF2fsPrimary) {
1316 if (!dm.GetDmDevicePathByName(android::base::Basename(device), &dmPath)) {
1317 LOG(WARNING) << "No proper dm device for " << device;
1318 isF2fsPrimary = false;
1319 }
1320 }
1321
1322 // Find a device name for F2FS primary partition
1323 std::string f2fsReservedBlocksSysfs;
1324 std::size_t leaf;
1325 if (isF2fsPrimary) {
1326 leaf = dmPath.rfind('/');
1327 if (leaf == std::string::npos) {
1328 LOG(WARNING) << "dm device " << dmPath << " is not a path";
1329 isF2fsPrimary = false;
1330 }
1331 f2fsReservedBlocksSysfs =
1332 std::string() + "/sys/fs/f2fs/" + dmPath.substr(leaf + 1) + "/reserved_blocks";
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001333 }
1334
1335 // Get the potential /sys/block entry
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001336 leaf = dataDevice.rfind('/');
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001337 if (leaf == std::string::npos) {
1338 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1339 return EINVAL;
1340 }
1341 if (dataDevice.substr(0, leaf) != "/dev/block") {
1342 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1343 return EINVAL;
1344 }
1345 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1346
1347 // Look for a directory in /sys/block containing size where the name is a shortened
1348 // version of the name we now have
1349 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1350 // Note that this directory only contains actual disks, not partitions, so this is
1351 // not going to find anything other than the disks
1352 std::string size;
1353 std::string sizeFile;
1354 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1355 if (sysfsDir.back() == '/') {
1356 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1357 return EINVAL;
1358 }
1359 sizeFile = sysfsDir + "/size";
1360 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1361 break;
1362 }
1363 }
1364
1365 // Read the size file and be done
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001366 int64_t sizeNum;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001367 std::stringstream ssSize(size);
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001368 ssSize >> sizeNum;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001369 if (ssSize.fail()) {
1370 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1371 return EINVAL;
1372 }
1373
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001374 sizeNum *= 512;
1375 if (isF2fsPrimary) {
1376 int64_t reservedBlocksNum = 0;
1377 if (!android::base::ReadFileToString(f2fsReservedBlocksSysfs, &size, true)) {
1378 LOG(WARNING) << "Could not find valid entry from " << f2fsReservedBlocksSysfs;
1379 } else {
1380 std::stringstream reservedBlocks(size);
1381 reservedBlocks >> reservedBlocksNum;
1382 if (reservedBlocks.fail()) {
1383 LOG(WARNING) << f2fsReservedBlocksSysfs << " cannot be read as an integer";
1384 reservedBlocksNum = 0;
1385 }
1386 }
1387 int64_t blockSize = android::base::GetIntProperty("ro.boot.hardware.cpu.pagesize", 0);
1388 sizeNum -= reservedBlocksNum * blockSize;
1389 }
1390
1391 *storageSize = sizeNum;
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001392 return OK;
Christopher Ferris71aafb12024-08-04 03:38:29 +00001393}
Daeho Jeong3da20f42024-11-13 13:25:16 -08001394
1395android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1396 android::status_t status;
1397 // Start with the /data mount point from fs_mgr
1398 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1399 if (entry == nullptr) {
1400 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1401 return EINVAL;
1402 }
1403
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001404 status = getDeviceSize(entry->blk_device, storageSize, entry->fs_type == "f2fs");
Daeho Jeong3da20f42024-11-13 13:25:16 -08001405 if (status != OK) {
1406 return status;
1407 }
1408
1409 for (auto device : entry->user_devices) {
1410 int64_t deviceStorageSize;
Daeho Jeong06a1e0e2025-02-06 13:18:47 -08001411 status = getDeviceSize(device, &deviceStorageSize, false);
Daeho Jeong3da20f42024-11-13 13:25:16 -08001412 if (status != OK) {
1413 return status;
1414 }
1415 *storageSize += deviceStorageSize;
1416 }
1417
1418 return OK;
1419}