blob: a1ac20d46608a14e3f71de0a6e6da627aca2a6f5 [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Ricky Waie96b34f2020-05-07 16:01:33 +010022#include <limits.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080023#include <mntent.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/ioctl.h>
28#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080029#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070030#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070031#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070032#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080033#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070034#include <array>
San Mehata19b2502010-01-06 10:33:53 -080035
San Mehata2677e42009-12-13 10:40:18 -080036#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070037
Paul Lawrenced73dfd42023-08-11 10:27:24 -070038#include <android-base/file.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060041#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080042#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070043#include <android-base/strings.h>
Narayan Kamath02efdf52019-11-27 10:53:51 +000044#include <async_safe/log.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070045
Jeff Sharkey71ebe152013-09-17 17:24:38 -070046#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060047#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070048
Robert Craigb9e3ba52014-02-04 10:53:00 -050049#include <selinux/android.h>
50
San Mehatfd7f5872009-10-12 11:32:47 -070051#include <sysutils/NetlinkEvent.h>
52
Kenny Root344ca102012-04-03 17:23:01 -070053#include <private/android_filesystem_config.h>
54
Eric Biggersa701c452018-10-23 13:06:55 -070055#include <fscrypt/fscrypt.h>
Paul Lawrenced73dfd42023-08-11 10:27:24 -070056#include <libdm/dm.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070057
Risanac02a482018-10-31 21:59:47 -060058#include "AppFuseUtil.h"
Eric Biggersa701c452018-10-23 13:06:55 -070059#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080060#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070061#include "NetlinkManager.h"
62#include "Process.h"
63#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070064#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070065#include "VoldUtil.h"
66#include "VolumeManager.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070067#include "fs/Ext4.h"
68#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070069#include "model/EmulatedVolume.h"
70#include "model/ObbVolume.h"
Zima438b242019-09-25 14:37:38 +010071#include "model/PrivateVolume.h"
himanshuz0ad08622023-07-27 21:15:00 +000072#include "model/PublicVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090073#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080074
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000075using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070076using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070077using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070078using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070079using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060080using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080081using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000082using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080083using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080084using android::vold::DeleteDirContentsAndDir;
Ricky Wai07e64a42020-02-11 14:31:24 +000085using android::vold::EnsureDirExists;
Martijn Coenen73e30102022-07-12 08:11:02 +000086using android::vold::GetFuseMountPathForUser;
Martijn Coenen62a4b272020-01-31 15:23:09 +010087using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070088using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070089using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010090using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010091using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010092using android::vold::PrivateVolume;
himanshuz0ad08622023-07-27 21:15:00 +000093using android::vold::PublicVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080094using android::vold::Symlink;
95using android::vold::Unlink;
96using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080097using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010098using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070099
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600100static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
101
102static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
103
Sudheer Shanka53947a32018-08-01 10:24:13 -0700104static const std::string kEmptyString("");
105
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600106/* 512MiB is large enough for testing purposes */
107static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700108
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700109static const unsigned int kMajorBlockMmc = 179;
110
Ricky Wai07e64a42020-02-11 14:31:24 +0000111using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
112
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700113VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700114
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700115VolumeManager* VolumeManager::Instance() {
116 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700117 return sInstance;
118}
119
120VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800121 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600122 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900123 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700124 // For security reasons, assume that a secure keyguard is
125 // showing until we hear otherwise
126 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700127}
128
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700129VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800130
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600131int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600132 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700133 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600134 if (access(kPathVirtualDisk, F_OK) != 0) {
135 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
136 }
137
138 if (mVirtualDisk == nullptr) {
139 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
140 LOG(ERROR) << "Failed to create virtual disk";
141 return -1;
142 }
143
144 struct stat buf;
145 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
146 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
147 return -1;
148 }
149
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700150 auto disk = new android::vold::Disk(
151 "virtual", buf.st_rdev, "virtual",
152 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600153 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700154 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600155 }
156 } else {
157 if (mVirtualDisk != nullptr) {
158 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700159 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600160
161 Loop::destroyByDevice(mVirtualDiskPath.c_str());
162 mVirtualDisk = nullptr;
163 }
164
165 if (access(kPathVirtualDisk, F_OK) == 0) {
166 unlink(kPathVirtualDisk);
167 }
168 }
169 return 0;
170}
171
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700172int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800173 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700174 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800175}
176
San Mehatf1b736b2009-10-10 17:22:08 -0700177int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600178 ATRACE_NAME("VolumeManager::start");
179
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700180 // Always start from a clean slate by unmounting everything in
181 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700182 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700183
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600184 Loop::destroyAll();
185
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700186 // Assume that we always have an emulated volume on internal
187 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100188 CHECK(mInternalEmulatedVolumes.empty());
189
190 auto vol = std::shared_ptr<android::vold::VolumeBase>(
191 new android::vold::EmulatedVolume("/data/media", 0));
192 vol->setMountUserId(0);
193 vol->create();
194 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700195
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600196 // Consider creating a virtual disk
197 updateVirtualDisk();
198
San Mehatf1b736b2009-10-10 17:22:08 -0700199 return 0;
200}
201
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700202void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700203 std::lock_guard<std::mutex> lock(mLock);
204
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700205 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700206 LOG(DEBUG) << "----------------";
207 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700208 evt->dump();
209 }
San Mehatf1b736b2009-10-10 17:22:08 -0700210
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700211 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
212 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700213
214 if (devType != "disk") return;
215
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600216 int major = std::stoi(evt->findParam("MAJOR"));
217 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700218 dev_t device = makedev(major, minor);
219
220 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700221 case NetlinkEvent::Action::kAdd: {
222 for (const auto& source : mDiskSources) {
223 if (source->matches(eventPath)) {
224 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700225 // specific to virtual platforms; see Utils.cpp for details)
226 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700227 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700228 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700229 flags |= android::vold::Disk::Flags::kSd;
230 } else {
231 flags |= android::vold::Disk::Flags::kUsb;
232 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700233
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700234 auto disk =
235 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
236 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
237 break;
238 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700239 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700240 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700241 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700242 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100243 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700244 handleDiskChanged(device);
245 break;
246 }
247 case NetlinkEvent::Action::kRemove: {
248 handleDiskRemoved(device);
249 break;
250 }
251 default: {
252 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
253 break;
254 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700255 }
256}
257
Jeff Sharkey401b2602017-12-14 22:15:20 -0700258void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
259 // For security reasons, if secure keyguard is showing, wait
260 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100261 // Additionally, wait until user 0 is actually started, since we need
262 // the user to be up before we can mount a FUSE daemon to handle the disk.
263 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700264 if (mSecureKeyguardShowing) {
265 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700266 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700267 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100268 } else if (!userZeroStarted) {
269 LOG(INFO) << "Found disk at " << disk->getEventPath()
270 << " but delaying scan due to user zero not having started";
271 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700272 } else {
273 disk->create();
274 mDisks.push_back(disk);
275 }
276}
277
278void VolumeManager::handleDiskChanged(dev_t device) {
279 for (const auto& disk : mDisks) {
280 if (disk->getDevice() == device) {
281 disk->readMetadata();
282 disk->readPartitions();
283 }
284 }
285
286 // For security reasons, we ignore all pending disks, since
287 // we'll scan them once the device is unlocked
288}
289
290void VolumeManager::handleDiskRemoved(dev_t device) {
291 auto i = mDisks.begin();
292 while (i != mDisks.end()) {
293 if ((*i)->getDevice() == device) {
294 (*i)->destroy();
295 i = mDisks.erase(i);
296 } else {
297 ++i;
298 }
299 }
300 auto j = mPendingDisks.begin();
301 while (j != mPendingDisks.end()) {
302 if ((*j)->getDevice() == device) {
303 j = mPendingDisks.erase(j);
304 } else {
305 ++j;
306 }
307 }
308}
309
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700310void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800311 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700312 mDiskSources.push_back(diskSource);
313}
314
315std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
316 for (auto disk : mDisks) {
317 if (disk->getId() == id) {
318 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700319 }
320 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321 return nullptr;
322}
San Mehatf1b736b2009-10-10 17:22:08 -0700323
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700324std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100325 for (const auto& vol : mInternalEmulatedVolumes) {
326 if (vol->getId() == id) {
327 return vol;
328 }
San Mehatf1b736b2009-10-10 17:22:08 -0700329 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700330 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700331 auto vol = disk->findVolume(id);
332 if (vol != nullptr) {
333 return vol;
334 }
335 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600336 for (const auto& vol : mObbVolumes) {
337 if (vol->getId() == id) {
338 return vol;
339 }
340 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700341 return nullptr;
342}
343
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800344void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
345 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700346 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700347 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700348 disk->listVolumes(type, list);
349 }
350}
351
Eric Biggers78627292023-08-01 22:36:55 +0000352bool VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700353 std::string normalizedGuid;
354 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
355 LOG(WARNING) << "Invalid GUID " << partGuid;
Eric Biggers78627292023-08-01 22:36:55 +0000356 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700357 }
358
359 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
360 if (unlink(keyPath.c_str()) != 0) {
361 LOG(ERROR) << "Failed to unlink " << keyPath;
Eric Biggers78627292023-08-01 22:36:55 +0000362 return false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700363 }
Eric Biggers78627292023-08-01 22:36:55 +0000364 return true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700365}
366
Zima438b242019-09-25 14:37:38 +0100367void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
368 // Destroy and remove all unstacked EmulatedVolumes for the user
369 auto i = mInternalEmulatedVolumes.begin();
370 while (i != mInternalEmulatedVolumes.end()) {
371 auto vol = *i;
372 if (vol->getMountUserId() == userId) {
373 vol->destroy();
374 i = mInternalEmulatedVolumes.erase(i);
375 } else {
376 i++;
377 }
378 }
379
380 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
381 std::list<std::string> private_vols;
382 listVolumes(VolumeBase::Type::kPrivate, private_vols);
383 for (const std::string& id : private_vols) {
384 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
385 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
386 if (pvol->getState() == VolumeBase::State::kMounted) {
387 for (const auto& vol : pvol->getVolumes()) {
388 if (vol->getMountUserId() == userId) {
389 vols_to_remove.push_back(vol);
390 }
391 }
392 for (const auto& vol : vols_to_remove) {
393 vol->destroy();
394 pvol->removeVolume(vol);
395 }
396 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
397 }
398}
399
400void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
401 // Create unstacked EmulatedVolumes for the user
402 auto vol = std::shared_ptr<android::vold::VolumeBase>(
403 new android::vold::EmulatedVolume("/data/media", userId));
404 vol->setMountUserId(userId);
405 mInternalEmulatedVolumes.push_back(vol);
406 vol->create();
407
408 // Create stacked EmulatedVolumes for the user on each PrivateVolume
409 std::list<std::string> private_vols;
410 listVolumes(VolumeBase::Type::kPrivate, private_vols);
411 for (const std::string& id : private_vols) {
412 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
413 if (pvol->getState() == VolumeBase::State::kMounted) {
414 auto evol =
415 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
416 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
417 userId));
418 evol->setMountUserId(userId);
419 pvol->addVolume(evol);
420 evol->create();
421 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
422 }
423}
424
Martijn Coenen73e30102022-07-12 08:11:02 +0000425userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
426 if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
427 return USER_UNKNOWN;
428 }
429 return mSharedStorageUser.at(userId);
430}
431
432int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
433 userid_t sharesStorageWithUserId) {
Zima438b242019-09-25 14:37:38 +0100434 LOG(INFO) << "onUserAdded: " << userId;
435
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700436 mAddedUsers[userId] = userSerialNumber;
Martijn Coenen73e30102022-07-12 08:11:02 +0000437 if (sharesStorageWithUserId != USER_UNKNOWN) {
438 mSharedStorageUser[userId] = sharesStorageWithUserId;
439 }
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700440 return 0;
441}
442
443int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100444 LOG(INFO) << "onUserRemoved: " << userId;
445
Zim2d45d9b2019-11-14 16:19:05 +0000446 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700447 mAddedUsers.erase(userId);
Martijn Coenen73e30102022-07-12 08:11:02 +0000448 mSharedStorageUser.erase(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700449 return 0;
450}
451
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700452int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100453 LOG(INFO) << "onUserStarted: " << userId;
454
Zim2d45d9b2019-11-14 16:19:05 +0000455 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
456 createEmulatedVolumesForUser(userId);
himanshuz0ad08622023-07-27 21:15:00 +0000457 std::list<std::string> public_vols;
458 listVolumes(VolumeBase::Type::kPublic, public_vols);
459 for (const std::string& id : public_vols) {
460 PublicVolume* pvol = static_cast<PublicVolume*>(findVolume(id).get());
461 if (pvol->getState() != VolumeBase::State::kMounted) {
462 continue;
463 }
464 if (pvol->isVisible() == 0) {
465 continue;
466 }
467 userid_t mountUserId = pvol->getMountUserId();
468 if (userId == mountUserId) {
469 // No need to bind mount for the user that owns the mount
470 continue;
471 }
472 if (mountUserId != VolumeManager::Instance()->getSharedStorageUser(userId)) {
473 // No need to bind if the user does not share storage with the mount owner
474 continue;
475 }
476 auto bindMountStatus = pvol->bindMountForUser(userId);
477 if (bindMountStatus != OK) {
478 LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
479 << "Failed. Error: " << bindMountStatus;
480 }
481 }
Zim2d45d9b2019-11-14 16:19:05 +0000482 }
483
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700484 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100485
486 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700487 return 0;
488}
489
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700490int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700491 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100492
Zim2d45d9b2019-11-14 16:19:05 +0000493 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100494 destroyEmulatedVolumesForUser(userId);
495 }
496
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700497 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700498 return 0;
499}
500
Martijn Coenencf5916f2020-01-03 14:36:45 +0100501void VolumeManager::createPendingDisksIfNeeded() {
502 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
503 if (!mSecureKeyguardShowing && userZeroStarted) {
504 // Now that secure keyguard has been dismissed and user 0 has
505 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700506 for (const auto& disk : mPendingDisks) {
507 disk->create();
508 mDisks.push_back(disk);
509 }
510 mPendingDisks.clear();
511 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100512}
513
514int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
515 mSecureKeyguardShowing = isShowing;
516 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700517 return 0;
518}
519
Narayan Kamath02efdf52019-11-27 10:53:51 +0000520// This code is executed after a fork so it's very important that the set of
521// methods we call here is strictly limited.
522//
523// TODO: Get rid of this guesswork altogether and instead exec a process
524// immediately after fork to do our bindding for us.
525static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000526 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000527 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000528 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000529 strerror(errno));
530 return false;
531 }
532
533 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
534 // to also protect against future changes that may cause issues across a
535 // fork.
536 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
537 errno != ENOENT) {
538 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
539 strerror(errno));
540 return false;
541 }
542
543 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
544 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000545 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000546 return false;
547 }
548
549 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
550 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000551 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000552 strerror(errno));
553 return false;
554 }
555
556 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
557 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000558 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000559 return false;
560 }
561
562 return true;
563}
564
Ricky Wai07e64a42020-02-11 14:31:24 +0000565// Fork the process and remount storage
566bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
567 int32_t mountMode = *static_cast<int32_t*>(params);
568 std::string userSource;
569 std::string storageSource;
570 pid_t child;
571 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800572 switch (mountMode) {
573 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000574 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800575 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000576 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800577 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000578 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700579 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000580 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800581 break;
Zim981222f2019-09-09 10:24:44 +0100582 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000583 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800584 default:
585 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000586 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800587 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000588 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700589
Ricky Wai07e64a42020-02-11 14:31:24 +0000590 // Fork a child to mount user-specific symlink helper into place
591 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
592 if (!(child = fork())) {
593 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
594 _exit(0);
595 } else {
596 _exit(1);
597 }
598 }
599
600 if (child == -1) {
601 PLOG(ERROR) << "Failed to fork";
602 return false;
603 } else {
604 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
605 }
606 return true;
607}
608
609// Helper function to scan all processes in /proc and call the callback if:
610// 1). pid belongs to an app process
611// 2). If input uid is 0 or it matches the process uid
612// 3). If userId is not -1 or userId matches the process userId
613bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700614 DIR* dir;
615 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600616 std::string rootName;
617 std::string pidName;
Jooyung Hana9f21712023-08-25 15:38:12 +0900618 std::string exeName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700619 int pidFd;
620 int nsFd;
621 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700622
623 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000624 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
625 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700626 }
627
628 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600629 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000630 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700631 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000632 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700633 }
634
Ricky Wai07e64a42020-02-11 14:31:24 +0000635 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700636 // Poke through all running PIDs look for apps running as UID
637 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700638 pid_t pid;
639 if (de->d_type != DT_DIR) continue;
640 if (!android::base::ParseInt(de->d_name, &pid)) continue;
641
Jeff Sharkey66270a22015-06-24 11:49:24 -0700642 pidFd = -1;
643 nsFd = -1;
644
645 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
646 if (pidFd < 0) {
647 goto next;
648 }
649 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000650 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700651 goto next;
652 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000653 if (uid != 0 && sb.st_uid != uid) {
654 goto next;
655 }
656 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700657 goto next;
658 }
659
660 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600661 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000662 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
663 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700664 goto next;
665 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600666 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700667 goto next;
668 }
669
Jooyung Hana9f21712023-08-25 15:38:12 +0900670 // Some early native processes have mount namespaces that are different
671 // from that of the init. Therefore, above check can't filter them out.
672 // Since the propagation type of / is 'shared', unmounting /storage
673 // for the early native processes affects other processes including
674 // init. Filter out such processes by skipping if a process is a
675 // non-Java process whose UID is < AID_APP_START. (The UID condition
676 // is required to not filter out child processes spawned by apps.)
677 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
678 goto next;
679 }
680 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
681 goto next;
Jiyong Park8d21c922019-01-04 13:35:25 +0900682 }
683
Jeff Sharkey66270a22015-06-24 11:49:24 -0700684 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700685 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
686 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700687 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000688 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
689 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700690 goto next;
691 }
692
Ricky Wai07e64a42020-02-11 14:31:24 +0000693 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
694 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700695 }
696
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700697 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700698 close(nsFd);
699 close(pidFd);
700 }
701 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000702 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
703 return true;
704}
705
Ricky Waia2ca11e2021-01-15 14:03:23 +0000706// In each app's namespace, unmount obb and data dirs
707static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
708 int uid, const char* targets[], int size) {
709 // This code is executed after a fork so it's very important that the set of
710 // methods we call here is strictly limited.
711 if (setns(nsFd, CLONE_NEWNS) != 0) {
712 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
713 return false;
714 }
715
716 // Unmount of Android/data/foo needs to be done before Android/data below.
717 bool result = true;
718 for (int i = 0; i < size; i++) {
719 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
720 errno != ENOENT) {
721 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
722 targets[i], strerror(errno));
723 result = false;
724 }
725 }
726
727 // Mount tmpfs on Android/data and Android/obb
728 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
729 errno != ENOENT) {
730 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
731 android_data_dir, strerror(errno));
732 result = false;
733 }
734 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
735 errno != ENOENT) {
736 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
737 android_obb_dir, strerror(errno));
738 result = false;
739 }
740 return result;
741}
742
Ricky Waie96b34f2020-05-07 16:01:33 +0100743// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
744// package dirs.
745static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
746 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000747 // This code is executed after a fork so it's very important that the set of
748 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000749 if (setns(nsFd, CLONE_NEWNS) != 0) {
750 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
751 return false;
752 }
753
Ricky Waie96b34f2020-05-07 16:01:33 +0100754 // Mount tmpfs on Android/data and Android/obb
755 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
756 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
757 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
758 android_data_dir, strerror(errno));
759 return false;
760 }
761 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
762 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
763 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
764 android_obb_dir, strerror(errno));
765 return false;
766 }
767
Ricky Wai6b122572020-02-28 16:30:47 +0000768 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100769 // Create package dir and bind mount it to the actual one.
770 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
771 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
772 targets[i], strerror(errno));
773 return false;
774 }
Ricky Wai6b122572020-02-28 16:30:47 +0000775 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
776 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
777 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000778 return false;
779 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000780 }
781 return true;
782}
783
Ricky Wai6b122572020-02-28 16:30:47 +0000784static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
785 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700786 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000787 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
788 userId, dirName.c_str(), packageName.c_str());
789 } else {
790 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
791 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000792 }
Ricky Wai6b122572020-02-28 16:30:47 +0000793}
794
795static std::string getStorageDirTarget(userid_t userId, std::string dirName,
796 std::string packageName) {
797 return StringPrintf("/storage/emulated/%d/%s/%s",
798 userId, dirName.c_str(), packageName.c_str());
799}
800
Ricky Waia2ca11e2021-01-15 14:03:23 +0000801// Fork the process and remount / unmount app data and obb dirs
802bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000803 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000804 userid_t userId = multiuser_get_user_id(uid);
805 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
806 android::base::unique_fd nsFd(
807 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
808 if (nsFd == -1) {
809 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
810 return false;
811 }
812 // Storing both Android/obb and Android/data paths.
813 int size = packageNames.size() * 2;
814
815 std::unique_ptr<std::string[]> sources(new std::string[size]);
816 std::unique_ptr<std::string[]> targets(new std::string[size]);
817 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
818 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
819 const char** sources_cstr = sources_uptr.get();
820 const char** targets_cstr = targets_uptr.get();
821
822 for (int i = 0; i < size; i += 2) {
823 std::string const& packageName = packageNames[i/2];
824 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
825 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
826 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
827 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
828
829 sources_cstr[i] = sources[i].c_str();
830 targets_cstr[i] = targets[i].c_str();
831 sources_cstr[i+1] = sources[i+1].c_str();
832 targets_cstr[i+1] = targets[i+1].c_str();
833 }
834
835 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000836 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000837 // This needs to be done before EnsureDirExists to ensure Android/ is created.
838 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000839 if (status != OK) {
840 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
841 return false;
842 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000843 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
844 if (status != OK) {
845 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
846 return false;
847 }
Ricky Wai6b122572020-02-28 16:30:47 +0000848 }
849
Ricky Waie96b34f2020-05-07 16:01:33 +0100850 char android_data_dir[PATH_MAX];
851 char android_obb_dir[PATH_MAX];
852 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
853 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
854
Ricky Wai6b122572020-02-28 16:30:47 +0000855 pid_t child;
856 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
857 // original vold process mount namespace.
858 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000859 if (doUnmount) {
860 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
861 targets_cstr, size)) {
862 _exit(0);
863 } else {
864 _exit(1);
865 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000866 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000867 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
868 sources_cstr, targets_cstr, size)) {
869 _exit(0);
870 } else {
871 _exit(1);
872 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000873 }
874 }
Ricky Wai6b122572020-02-28 16:30:47 +0000875
Ricky Wai07e64a42020-02-11 14:31:24 +0000876 if (child == -1) {
877 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000878 return false;
879 } else {
880 int status;
881 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
882 PLOG(ERROR) << "Failed to waitpid: " << child;
883 return false;
884 }
885 if (!WIFEXITED(status)) {
886 PLOG(ERROR) << "Process did not exit normally, status: " << status;
887 return false;
888 }
889 if (WEXITSTATUS(status)) {
890 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
891 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000892 }
893 }
Ricky Wai6b122572020-02-28 16:30:47 +0000894 return true;
895}
896
Ricky Waia2ca11e2021-01-15 14:03:23 +0000897int VolumeManager::handleAppStorageDirs(int uid, int pid,
898 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000899 // Only run the remount if fuse is mounted for that user.
900 userid_t userId = multiuser_get_user_id(uid);
901 bool fuseMounted = false;
902 for (auto& vol : mInternalEmulatedVolumes) {
903 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
904 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
905 if (emulatedVol) {
906 fuseMounted = emulatedVol->isFuseMounted();
907 }
908 break;
909 }
910 }
911 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000912 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000913 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700914 return 0;
915}
916
Martijn Coenen23c04452020-04-29 07:49:41 +0200917int VolumeManager::abortFuse() {
918 return android::vold::AbortFuseConnections();
919}
920
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700921int VolumeManager::reset() {
922 // Tear down all existing disks/volumes and start from a blank slate so
923 // newly connected framework hears all events.
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900924
925 // Destroy StubVolume disks. This needs to be done before destroying
926 // EmulatedVolumes because in ARC (Android on ChromeOS), ChromeOS Downloads
927 // directory (which is in a StubVolume) is bind-mounted to
928 // /data/media/0/Download.
929 // We do not recreate StubVolumes here because they are managed from outside
930 // Android (e.g. from ChromeOS) and their disk recreation on reset events
931 // should be handled from outside by calling createStubVolume() again.
932 for (const auto& disk : mDisks) {
933 if (disk->isStub()) {
934 disk->destroy();
935 }
936 }
937 // Remove StubVolume from both mDisks and mPendingDisks.
938 const auto isStub = [](const auto& disk) { return disk->isStub(); };
939 mDisks.remove_if(isStub);
940 mPendingDisks.remove_if(isStub);
941
Zima438b242019-09-25 14:37:38 +0100942 for (const auto& vol : mInternalEmulatedVolumes) {
943 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800944 }
Zima438b242019-09-25 14:37:38 +0100945 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100946
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900947 // Destroy and recreate non-StubVolume disks.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700948 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700949 disk->destroy();
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900950 disk->create();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700951 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900952
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600953 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700954 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800955 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +0000956 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +0100957
958 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
959 // with FUSE fds open.
960 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700961 return 0;
962}
963
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700964// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700965int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100966 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700967 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700968 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700969 android::vold::sSleepOnUnmount = false;
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900970 // Destroy StubVolume disks before destroying EmulatedVolumes (see the
971 // comment in VolumeManager::reset()).
972 for (const auto& disk : mDisks) {
973 if (disk->isStub()) {
974 disk->destroy();
975 }
976 }
Zima438b242019-09-25 14:37:38 +0100977 for (const auto& vol : mInternalEmulatedVolumes) {
978 vol->destroy();
979 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700980 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900981 if (!disk->isStub()) {
982 disk->destroy();
983 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700984 }
Zima438b242019-09-25 14:37:38 +0100985
986 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700987 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700988 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700989 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200990
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700991 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700992}
993
Jeff Sharkey9c484982015-03-31 10:35:33 -0700994int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700995 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600996 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700997
Jeff Sharkey9c484982015-03-31 10:35:33 -0700998 // First, try gracefully unmounting all known devices
Momoko Hattorib4e033e2024-02-22 16:07:24 +0900999 // Unmount StubVolume disks before unmounting EmulatedVolumes (see the
1000 // comment in VolumeManager::reset()).
1001 for (const auto& disk : mDisks) {
1002 if (disk->isStub()) {
1003 disk->unmountAll();
1004 }
1005 }
Zima438b242019-09-25 14:37:38 +01001006 for (const auto& vol : mInternalEmulatedVolumes) {
1007 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -07001008 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001009 for (const auto& disk : mDisks) {
Momoko Hattorib4e033e2024-02-22 16:07:24 +09001010 if (!disk->isStub()) {
1011 disk->unmountAll();
1012 }
Jeff Sharkey9c484982015-03-31 10:35:33 -07001013 }
1014
1015 // Worst case we might have some stale mounts lurking around, so
1016 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001017 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001018 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001019 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001020 return -errno;
1021 }
1022
1023 // Some volumes can be stacked on each other, so force unmount in
1024 // reverse order to give us the best chance of success.
1025 std::list<std::string> toUnmount;
1026 mntent* mentry;
1027 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001028 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001029 if ((StartsWith(test, "/mnt/") &&
1030#ifdef __ANDROID_DEBUGGABLE__
1031 !StartsWith(test, "/mnt/scratch") &&
1032#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +01001033 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +01001034 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001035 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001036 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001037 }
1038 }
1039 endmntent(fp);
1040
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001041 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001042 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001043 android::vold::ForceUnmount(path);
1044 }
1045
1046 return 0;
1047}
1048
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001049int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001050 int size = paths.size();
1051 for (int i = 0; i < size; i++) {
1052 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1053 true /* skipIfDirExists */);
1054 if (result != OK) {
1055 return result;
1056 }
1057 }
1058 return OK;
1059}
1060
1061int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1062 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001063 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001064 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001065 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001066 return -EINVAL;
1067 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001068
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001069 // Find the volume it belongs to
1070 auto filter_fn = [&](const VolumeBase& vol) {
1071 if (vol.getState() != VolumeBase::State::kMounted) {
1072 // The volume must be mounted
1073 return false;
1074 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001075 if (!vol.isVisibleForWrite()) {
1076 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001077 return false;
1078 }
1079 if (vol.getInternalPath().empty()) {
1080 return false;
1081 }
1082 if (vol.getMountUserId() != USER_UNKNOWN &&
1083 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1084 // The app dir must be created on a volume with the same user-id
1085 return false;
1086 }
1087 if (!path.empty() && StartsWith(path, vol.getPath())) {
1088 return true;
1089 }
1090
1091 return false;
1092 };
1093 auto volume = findVolumeWithFilter(filter_fn);
1094 if (volume == nullptr) {
1095 LOG(ERROR) << "Failed to find mounted volume for " << path;
1096 return -EINVAL;
1097 }
Zimc59d7742020-01-06 21:48:16 +00001098 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1099 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1100 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1101 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001102 const std::string lowerPath =
1103 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001104
Martijn Coenen62a4b272020-01-31 15:23:09 +01001105 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1106
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001107 const int access_result = access(lowerPath.c_str(), F_OK);
1108 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001109 // Nothing to fixup
1110 return OK;
1111 }
1112
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001113 if (skipIfDirExists && access_result == 0) {
1114 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1115 // which the dir doesn't need to have correct permission for now yet.
1116 return OK;
1117 }
1118
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001119 if (volume->getType() == VolumeBase::Type::kPublic) {
1120 // On public volumes, we don't need to setup permissions, as everything goes through
1121 // FUSE; just create the dirs and be done with it.
1122 return fs_mkdirs(lowerPath.c_str(), 0700);
1123 }
1124
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001125 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001126 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1127}
1128
1129int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001130 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001131 //sdcardfs magically does this for us
1132 return OK;
1133 }
1134 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001135}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001136
Eric Biggers7e79a432022-03-01 21:19:18 +00001137int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1138 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001139 int id = mNextObbId++;
1140
Martijn Coenend6a612a2020-11-19 10:49:45 +01001141 std::string lowerSourcePath;
1142
1143 // Convert to lower filesystem path
1144 if (StartsWith(sourcePath, "/storage/")) {
1145 auto filter_fn = [&](const VolumeBase& vol) {
1146 if (vol.getState() != VolumeBase::State::kMounted) {
1147 // The volume must be mounted
1148 return false;
1149 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001150 if (!vol.isVisibleForWrite()) {
1151 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001152 return false;
1153 }
1154 if (vol.getInternalPath().empty()) {
1155 return false;
1156 }
1157 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1158 return true;
1159 }
1160
1161 return false;
1162 };
1163 auto volume = findVolumeWithFilter(filter_fn);
1164 if (volume == nullptr) {
1165 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1166 return -EINVAL;
1167 } else {
1168 lowerSourcePath =
1169 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1170 }
1171 } else {
1172 lowerSourcePath = sourcePath;
1173 }
1174
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001175 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001176 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001177 vol->create();
1178
1179 mObbVolumes.push_back(vol);
1180 *outVolId = vol->getId();
1181 return android::OK;
1182}
1183
1184int VolumeManager::destroyObb(const std::string& volId) {
1185 auto i = mObbVolumes.begin();
1186 while (i != mObbVolumes.end()) {
1187 if ((*i)->getId() == volId) {
1188 (*i)->destroy();
1189 i = mObbVolumes.erase(i);
1190 } else {
1191 ++i;
1192 }
1193 }
1194 return android::OK;
1195}
1196
Risan8c9f3322018-10-29 08:52:56 +09001197int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1198 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001199 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001200 std::string* outVolId) {
1201 dev_t stubId = --mNextStubId;
1202 auto vol = std::shared_ptr<android::vold::StubVolume>(
1203 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001204
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001205 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001206 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1207 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001208 if (flags & android::vold::Disk::Flags::kStubVisible) {
1209 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1210 } else {
1211 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1212 }
Risan82e90de2020-02-04 16:07:21 +09001213 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001214 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001215 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001216 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001217 disk->initializePartition(vol);
1218 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001219 *outVolId = vol->getId();
1220 return android::OK;
1221}
1222
1223int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001224 auto tokens = android::base::Split(volId, ":");
1225 CHECK(tokens.size() == 2);
1226 dev_t stubId;
1227 CHECK(android::base::ParseUint(tokens[1], &stubId));
1228 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001229 return android::OK;
1230}
1231
Risan8f6198d2018-10-26 20:56:45 -06001232int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001233 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001234}
1235
Risan8f6198d2018-10-26 20:56:45 -06001236int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001237 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001238}
1239
1240int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001241 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001242}
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001243
1244android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1245 // Start with the /data mount point from fs_mgr
1246 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1247 if (entry == nullptr) {
1248 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1249 return EINVAL;
1250 }
1251
1252 // Follow any symbolic links
1253 std::string blkDevice = entry->blk_device;
1254 std::string dataDevice;
1255 if (!android::base::Realpath(blkDevice, &dataDevice)) {
1256 dataDevice = blkDevice;
1257 }
1258
1259 // Handle mapped volumes.
1260 auto& dm = android::dm::DeviceMapper::Instance();
1261 for (;;) {
1262 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1263 if (!parent.has_value()) break;
1264 dataDevice = *parent;
1265 }
1266
1267 // Get the potential /sys/block entry
1268 std::size_t leaf = dataDevice.rfind('/');
1269 if (leaf == std::string::npos) {
1270 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1271 return EINVAL;
1272 }
1273 if (dataDevice.substr(0, leaf) != "/dev/block") {
1274 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1275 return EINVAL;
1276 }
1277 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1278
1279 // Look for a directory in /sys/block containing size where the name is a shortened
1280 // version of the name we now have
1281 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1282 // Note that this directory only contains actual disks, not partitions, so this is
1283 // not going to find anything other than the disks
1284 std::string size;
1285 std::string sizeFile;
1286 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1287 if (sysfsDir.back() == '/') {
1288 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1289 return EINVAL;
1290 }
1291 sizeFile = sysfsDir + "/size";
1292 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1293 break;
1294 }
1295 }
1296
1297 // Read the size file and be done
1298 std::stringstream ssSize(size);
1299 ssSize >> *storageSize;
1300 if (ssSize.fail()) {
1301 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1302 return EINVAL;
1303 }
1304
1305 *storageSize *= 512;
1306 return OK;
1307}