blob: db356db3b4214d42714840c3f4610f3dc682ff36 [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
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600352int 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;
356 return -1;
357 }
358
Paul Crowleyc6433a22017-10-24 14:54:43 -0700359 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700360 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
361 if (unlink(keyPath.c_str()) != 0) {
362 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700363 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700364 }
Eric Biggersa6957c02022-06-15 18:52:18 +0000365 if (IsFbeEnabled()) {
Eric Biggersa701c452018-10-23 13:06:55 -0700366 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700367 success = false;
368 }
369 }
370 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700371}
372
Zima438b242019-09-25 14:37:38 +0100373void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
374 // Destroy and remove all unstacked EmulatedVolumes for the user
375 auto i = mInternalEmulatedVolumes.begin();
376 while (i != mInternalEmulatedVolumes.end()) {
377 auto vol = *i;
378 if (vol->getMountUserId() == userId) {
379 vol->destroy();
380 i = mInternalEmulatedVolumes.erase(i);
381 } else {
382 i++;
383 }
384 }
385
386 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
387 std::list<std::string> private_vols;
388 listVolumes(VolumeBase::Type::kPrivate, private_vols);
389 for (const std::string& id : private_vols) {
390 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
391 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
392 if (pvol->getState() == VolumeBase::State::kMounted) {
393 for (const auto& vol : pvol->getVolumes()) {
394 if (vol->getMountUserId() == userId) {
395 vols_to_remove.push_back(vol);
396 }
397 }
398 for (const auto& vol : vols_to_remove) {
399 vol->destroy();
400 pvol->removeVolume(vol);
401 }
402 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
403 }
404}
405
406void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
407 // Create unstacked EmulatedVolumes for the user
408 auto vol = std::shared_ptr<android::vold::VolumeBase>(
409 new android::vold::EmulatedVolume("/data/media", userId));
410 vol->setMountUserId(userId);
411 mInternalEmulatedVolumes.push_back(vol);
412 vol->create();
413
414 // Create stacked EmulatedVolumes for the user on each PrivateVolume
415 std::list<std::string> private_vols;
416 listVolumes(VolumeBase::Type::kPrivate, private_vols);
417 for (const std::string& id : private_vols) {
418 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
419 if (pvol->getState() == VolumeBase::State::kMounted) {
420 auto evol =
421 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
422 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
423 userId));
424 evol->setMountUserId(userId);
425 pvol->addVolume(evol);
426 evol->create();
427 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
428 }
429}
430
Martijn Coenen73e30102022-07-12 08:11:02 +0000431userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
432 if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
433 return USER_UNKNOWN;
434 }
435 return mSharedStorageUser.at(userId);
436}
437
438int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
439 userid_t sharesStorageWithUserId) {
Zima438b242019-09-25 14:37:38 +0100440 LOG(INFO) << "onUserAdded: " << userId;
441
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700442 mAddedUsers[userId] = userSerialNumber;
Martijn Coenen73e30102022-07-12 08:11:02 +0000443 if (sharesStorageWithUserId != USER_UNKNOWN) {
444 mSharedStorageUser[userId] = sharesStorageWithUserId;
445 }
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700446 return 0;
447}
448
449int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100450 LOG(INFO) << "onUserRemoved: " << userId;
451
Zim2d45d9b2019-11-14 16:19:05 +0000452 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700453 mAddedUsers.erase(userId);
Martijn Coenen73e30102022-07-12 08:11:02 +0000454 mSharedStorageUser.erase(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700455 return 0;
456}
457
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700458int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100459 LOG(INFO) << "onUserStarted: " << userId;
460
Zim2d45d9b2019-11-14 16:19:05 +0000461 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
462 createEmulatedVolumesForUser(userId);
himanshuz0ad08622023-07-27 21:15:00 +0000463 std::list<std::string> public_vols;
464 listVolumes(VolumeBase::Type::kPublic, public_vols);
465 for (const std::string& id : public_vols) {
466 PublicVolume* pvol = static_cast<PublicVolume*>(findVolume(id).get());
467 if (pvol->getState() != VolumeBase::State::kMounted) {
468 continue;
469 }
470 if (pvol->isVisible() == 0) {
471 continue;
472 }
473 userid_t mountUserId = pvol->getMountUserId();
474 if (userId == mountUserId) {
475 // No need to bind mount for the user that owns the mount
476 continue;
477 }
478 if (mountUserId != VolumeManager::Instance()->getSharedStorageUser(userId)) {
479 // No need to bind if the user does not share storage with the mount owner
480 continue;
481 }
482 auto bindMountStatus = pvol->bindMountForUser(userId);
483 if (bindMountStatus != OK) {
484 LOG(ERROR) << "Bind Mounting Public Volume: " << pvol << " for user: " << userId
485 << "Failed. Error: " << bindMountStatus;
486 }
487 }
Zim2d45d9b2019-11-14 16:19:05 +0000488 }
489
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700490 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100491
492 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700493 return 0;
494}
495
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700496int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700497 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100498
Zim2d45d9b2019-11-14 16:19:05 +0000499 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100500 destroyEmulatedVolumesForUser(userId);
501 }
502
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700503 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700504 return 0;
505}
506
Martijn Coenencf5916f2020-01-03 14:36:45 +0100507void VolumeManager::createPendingDisksIfNeeded() {
508 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
509 if (!mSecureKeyguardShowing && userZeroStarted) {
510 // Now that secure keyguard has been dismissed and user 0 has
511 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700512 for (const auto& disk : mPendingDisks) {
513 disk->create();
514 mDisks.push_back(disk);
515 }
516 mPendingDisks.clear();
517 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100518}
519
520int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
521 mSecureKeyguardShowing = isShowing;
522 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700523 return 0;
524}
525
Narayan Kamath02efdf52019-11-27 10:53:51 +0000526// This code is executed after a fork so it's very important that the set of
527// methods we call here is strictly limited.
528//
529// TODO: Get rid of this guesswork altogether and instead exec a process
530// immediately after fork to do our bindding for us.
531static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000532 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000533 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000534 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000535 strerror(errno));
536 return false;
537 }
538
539 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
540 // to also protect against future changes that may cause issues across a
541 // fork.
542 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
543 errno != ENOENT) {
544 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
545 strerror(errno));
546 return false;
547 }
548
549 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
550 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000551 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000552 return false;
553 }
554
555 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
556 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000557 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000558 strerror(errno));
559 return false;
560 }
561
562 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
563 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000564 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000565 return false;
566 }
567
568 return true;
569}
570
Ricky Wai07e64a42020-02-11 14:31:24 +0000571// Fork the process and remount storage
572bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
573 int32_t mountMode = *static_cast<int32_t*>(params);
574 std::string userSource;
575 std::string storageSource;
576 pid_t child;
577 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800578 switch (mountMode) {
579 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000580 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800581 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000582 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800583 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000584 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700585 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000586 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800587 break;
Zim981222f2019-09-09 10:24:44 +0100588 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000589 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800590 default:
591 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000592 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800593 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000594 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700595
Ricky Wai07e64a42020-02-11 14:31:24 +0000596 // Fork a child to mount user-specific symlink helper into place
597 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
598 if (!(child = fork())) {
599 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
600 _exit(0);
601 } else {
602 _exit(1);
603 }
604 }
605
606 if (child == -1) {
607 PLOG(ERROR) << "Failed to fork";
608 return false;
609 } else {
610 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
611 }
612 return true;
613}
614
615// Helper function to scan all processes in /proc and call the callback if:
616// 1). pid belongs to an app process
617// 2). If input uid is 0 or it matches the process uid
618// 3). If userId is not -1 or userId matches the process userId
619bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700620 DIR* dir;
621 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600622 std::string rootName;
623 std::string pidName;
Jooyung Hana9f21712023-08-25 15:38:12 +0900624 std::string exeName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700625 int pidFd;
626 int nsFd;
627 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700628
629 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000630 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
631 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700632 }
633
634 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600635 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000636 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700637 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000638 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700639 }
640
Ricky Wai07e64a42020-02-11 14:31:24 +0000641 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700642 // Poke through all running PIDs look for apps running as UID
643 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700644 pid_t pid;
645 if (de->d_type != DT_DIR) continue;
646 if (!android::base::ParseInt(de->d_name, &pid)) continue;
647
Jeff Sharkey66270a22015-06-24 11:49:24 -0700648 pidFd = -1;
649 nsFd = -1;
650
651 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
652 if (pidFd < 0) {
653 goto next;
654 }
655 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000656 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700657 goto next;
658 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000659 if (uid != 0 && sb.st_uid != uid) {
660 goto next;
661 }
662 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700663 goto next;
664 }
665
666 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600667 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000668 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
669 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700670 goto next;
671 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600672 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700673 goto next;
674 }
675
Jooyung Hana9f21712023-08-25 15:38:12 +0900676 // Some early native processes have mount namespaces that are different
677 // from that of the init. Therefore, above check can't filter them out.
678 // Since the propagation type of / is 'shared', unmounting /storage
679 // for the early native processes affects other processes including
680 // init. Filter out such processes by skipping if a process is a
681 // non-Java process whose UID is < AID_APP_START. (The UID condition
682 // is required to not filter out child processes spawned by apps.)
683 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
684 goto next;
685 }
686 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
687 goto next;
Jiyong Park8d21c922019-01-04 13:35:25 +0900688 }
689
Jeff Sharkey66270a22015-06-24 11:49:24 -0700690 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700691 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
692 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700693 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000694 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
695 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700696 goto next;
697 }
698
Ricky Wai07e64a42020-02-11 14:31:24 +0000699 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
700 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700701 }
702
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700703 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700704 close(nsFd);
705 close(pidFd);
706 }
707 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000708 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
709 return true;
710}
711
Ricky Waia2ca11e2021-01-15 14:03:23 +0000712// In each app's namespace, unmount obb and data dirs
713static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
714 int uid, const char* targets[], int size) {
715 // This code is executed after a fork so it's very important that the set of
716 // methods we call here is strictly limited.
717 if (setns(nsFd, CLONE_NEWNS) != 0) {
718 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
719 return false;
720 }
721
722 // Unmount of Android/data/foo needs to be done before Android/data below.
723 bool result = true;
724 for (int i = 0; i < size; i++) {
725 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
726 errno != ENOENT) {
727 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
728 targets[i], strerror(errno));
729 result = false;
730 }
731 }
732
733 // Mount tmpfs on Android/data and Android/obb
734 if (TEMP_FAILURE_RETRY(umount2(android_data_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_data_dir, strerror(errno));
738 result = false;
739 }
740 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
741 errno != ENOENT) {
742 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
743 android_obb_dir, strerror(errno));
744 result = false;
745 }
746 return result;
747}
748
Ricky Waie96b34f2020-05-07 16:01:33 +0100749// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
750// package dirs.
751static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
752 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000753 // This code is executed after a fork so it's very important that the set of
754 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000755 if (setns(nsFd, CLONE_NEWNS) != 0) {
756 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
757 return false;
758 }
759
Ricky Waie96b34f2020-05-07 16:01:33 +0100760 // Mount tmpfs on Android/data and Android/obb
761 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_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_data_dir, strerror(errno));
765 return false;
766 }
767 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
768 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
769 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
770 android_obb_dir, strerror(errno));
771 return false;
772 }
773
Ricky Wai6b122572020-02-28 16:30:47 +0000774 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100775 // Create package dir and bind mount it to the actual one.
776 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
777 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
778 targets[i], strerror(errno));
779 return false;
780 }
Ricky Wai6b122572020-02-28 16:30:47 +0000781 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
782 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
783 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000784 return false;
785 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000786 }
787 return true;
788}
789
Ricky Wai6b122572020-02-28 16:30:47 +0000790static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
791 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700792 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000793 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
794 userId, dirName.c_str(), packageName.c_str());
795 } else {
796 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
797 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000798 }
Ricky Wai6b122572020-02-28 16:30:47 +0000799}
800
801static std::string getStorageDirTarget(userid_t userId, std::string dirName,
802 std::string packageName) {
803 return StringPrintf("/storage/emulated/%d/%s/%s",
804 userId, dirName.c_str(), packageName.c_str());
805}
806
Ricky Waia2ca11e2021-01-15 14:03:23 +0000807// Fork the process and remount / unmount app data and obb dirs
808bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000809 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000810 userid_t userId = multiuser_get_user_id(uid);
811 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
812 android::base::unique_fd nsFd(
813 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
814 if (nsFd == -1) {
815 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
816 return false;
817 }
818 // Storing both Android/obb and Android/data paths.
819 int size = packageNames.size() * 2;
820
821 std::unique_ptr<std::string[]> sources(new std::string[size]);
822 std::unique_ptr<std::string[]> targets(new std::string[size]);
823 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
824 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
825 const char** sources_cstr = sources_uptr.get();
826 const char** targets_cstr = targets_uptr.get();
827
828 for (int i = 0; i < size; i += 2) {
829 std::string const& packageName = packageNames[i/2];
830 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
831 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
832 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
833 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
834
835 sources_cstr[i] = sources[i].c_str();
836 targets_cstr[i] = targets[i].c_str();
837 sources_cstr[i+1] = sources[i+1].c_str();
838 targets_cstr[i+1] = targets[i+1].c_str();
839 }
840
841 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000842 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000843 // This needs to be done before EnsureDirExists to ensure Android/ is created.
844 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000845 if (status != OK) {
846 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
847 return false;
848 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000849 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
850 if (status != OK) {
851 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
852 return false;
853 }
Ricky Wai6b122572020-02-28 16:30:47 +0000854 }
855
Ricky Waie96b34f2020-05-07 16:01:33 +0100856 char android_data_dir[PATH_MAX];
857 char android_obb_dir[PATH_MAX];
858 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
859 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
860
Ricky Wai6b122572020-02-28 16:30:47 +0000861 pid_t child;
862 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
863 // original vold process mount namespace.
864 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000865 if (doUnmount) {
866 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
867 targets_cstr, size)) {
868 _exit(0);
869 } else {
870 _exit(1);
871 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000872 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000873 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
874 sources_cstr, targets_cstr, size)) {
875 _exit(0);
876 } else {
877 _exit(1);
878 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000879 }
880 }
Ricky Wai6b122572020-02-28 16:30:47 +0000881
Ricky Wai07e64a42020-02-11 14:31:24 +0000882 if (child == -1) {
883 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000884 return false;
885 } else {
886 int status;
887 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
888 PLOG(ERROR) << "Failed to waitpid: " << child;
889 return false;
890 }
891 if (!WIFEXITED(status)) {
892 PLOG(ERROR) << "Process did not exit normally, status: " << status;
893 return false;
894 }
895 if (WEXITSTATUS(status)) {
896 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
897 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000898 }
899 }
Ricky Wai6b122572020-02-28 16:30:47 +0000900 return true;
901}
902
Ricky Waia2ca11e2021-01-15 14:03:23 +0000903int VolumeManager::handleAppStorageDirs(int uid, int pid,
904 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000905 // Only run the remount if fuse is mounted for that user.
906 userid_t userId = multiuser_get_user_id(uid);
907 bool fuseMounted = false;
908 for (auto& vol : mInternalEmulatedVolumes) {
909 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
910 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
911 if (emulatedVol) {
912 fuseMounted = emulatedVol->isFuseMounted();
913 }
914 break;
915 }
916 }
917 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000918 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000919 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700920 return 0;
921}
922
Martijn Coenen23c04452020-04-29 07:49:41 +0200923int VolumeManager::abortFuse() {
924 return android::vold::AbortFuseConnections();
925}
926
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700927int VolumeManager::reset() {
928 // Tear down all existing disks/volumes and start from a blank slate so
929 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100930 for (const auto& vol : mInternalEmulatedVolumes) {
931 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800932 }
Zima438b242019-09-25 14:37:38 +0100933 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100934
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900935 // Destroy and recreate all disks except that StubVolume disks are just
936 // destroyed and removed from both mDisks and mPendingDisks.
937 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
938 // their disk recreation on reset events should be handled from outside by
939 // calling createStubVolume() again.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700940 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700941 disk->destroy();
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900942 if (!disk->isStub()) {
943 disk->create();
944 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700945 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900946 const auto isStub = [](const auto& disk) { return disk->isStub(); };
947 mDisks.remove_if(isStub);
948 mPendingDisks.remove_if(isStub);
949
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600950 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700951 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800952 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +0000953 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +0100954
955 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
956 // with FUSE fds open.
957 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700958 return 0;
959}
960
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700961// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700962int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100963 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700964 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700965 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700966 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100967 for (const auto& vol : mInternalEmulatedVolumes) {
968 vol->destroy();
969 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700970 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700971 disk->destroy();
972 }
Zima438b242019-09-25 14:37:38 +0100973
974 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700975 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700976 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700977 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200978
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700979 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700980}
981
Jeff Sharkey9c484982015-03-31 10:35:33 -0700982int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700983 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600984 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700985
Jeff Sharkey9c484982015-03-31 10:35:33 -0700986 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100987 for (const auto& vol : mInternalEmulatedVolumes) {
988 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700989 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700990 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700991 disk->unmountAll();
992 }
993
994 // Worst case we might have some stale mounts lurking around, so
995 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800996 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700997 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600998 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700999 return -errno;
1000 }
1001
1002 // Some volumes can be stacked on each other, so force unmount in
1003 // reverse order to give us the best chance of success.
1004 std::list<std::string> toUnmount;
1005 mntent* mentry;
1006 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001007 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001008 if ((StartsWith(test, "/mnt/") &&
1009#ifdef __ANDROID_DEBUGGABLE__
1010 !StartsWith(test, "/mnt/scratch") &&
1011#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +01001012 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +01001013 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001014 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001015 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001016 }
1017 }
1018 endmntent(fp);
1019
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001020 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001021 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001022 android::vold::ForceUnmount(path);
1023 }
1024
1025 return 0;
1026}
1027
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001028int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001029 int size = paths.size();
1030 for (int i = 0; i < size; i++) {
1031 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1032 true /* skipIfDirExists */);
1033 if (result != OK) {
1034 return result;
1035 }
1036 }
1037 return OK;
1038}
1039
1040int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1041 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001042 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001043 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001044 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001045 return -EINVAL;
1046 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001047
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001048 // Find the volume it belongs to
1049 auto filter_fn = [&](const VolumeBase& vol) {
1050 if (vol.getState() != VolumeBase::State::kMounted) {
1051 // The volume must be mounted
1052 return false;
1053 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001054 if (!vol.isVisibleForWrite()) {
1055 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001056 return false;
1057 }
1058 if (vol.getInternalPath().empty()) {
1059 return false;
1060 }
1061 if (vol.getMountUserId() != USER_UNKNOWN &&
1062 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1063 // The app dir must be created on a volume with the same user-id
1064 return false;
1065 }
1066 if (!path.empty() && StartsWith(path, vol.getPath())) {
1067 return true;
1068 }
1069
1070 return false;
1071 };
1072 auto volume = findVolumeWithFilter(filter_fn);
1073 if (volume == nullptr) {
1074 LOG(ERROR) << "Failed to find mounted volume for " << path;
1075 return -EINVAL;
1076 }
Zimc59d7742020-01-06 21:48:16 +00001077 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1078 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1079 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1080 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001081 const std::string lowerPath =
1082 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001083
Martijn Coenen62a4b272020-01-31 15:23:09 +01001084 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1085
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001086 const int access_result = access(lowerPath.c_str(), F_OK);
1087 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001088 // Nothing to fixup
1089 return OK;
1090 }
1091
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001092 if (skipIfDirExists && access_result == 0) {
1093 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1094 // which the dir doesn't need to have correct permission for now yet.
1095 return OK;
1096 }
1097
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001098 if (volume->getType() == VolumeBase::Type::kPublic) {
1099 // On public volumes, we don't need to setup permissions, as everything goes through
1100 // FUSE; just create the dirs and be done with it.
1101 return fs_mkdirs(lowerPath.c_str(), 0700);
1102 }
1103
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001104 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001105 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1106}
1107
1108int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001109 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001110 //sdcardfs magically does this for us
1111 return OK;
1112 }
1113 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001114}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001115
Eric Biggers7e79a432022-03-01 21:19:18 +00001116int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1117 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001118 int id = mNextObbId++;
1119
Martijn Coenend6a612a2020-11-19 10:49:45 +01001120 std::string lowerSourcePath;
1121
1122 // Convert to lower filesystem path
1123 if (StartsWith(sourcePath, "/storage/")) {
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 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001131 return false;
1132 }
1133 if (vol.getInternalPath().empty()) {
1134 return false;
1135 }
1136 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1137 return true;
1138 }
1139
1140 return false;
1141 };
1142 auto volume = findVolumeWithFilter(filter_fn);
1143 if (volume == nullptr) {
1144 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1145 return -EINVAL;
1146 } else {
1147 lowerSourcePath =
1148 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1149 }
1150 } else {
1151 lowerSourcePath = sourcePath;
1152 }
1153
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001154 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001155 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001156 vol->create();
1157
1158 mObbVolumes.push_back(vol);
1159 *outVolId = vol->getId();
1160 return android::OK;
1161}
1162
1163int VolumeManager::destroyObb(const std::string& volId) {
1164 auto i = mObbVolumes.begin();
1165 while (i != mObbVolumes.end()) {
1166 if ((*i)->getId() == volId) {
1167 (*i)->destroy();
1168 i = mObbVolumes.erase(i);
1169 } else {
1170 ++i;
1171 }
1172 }
1173 return android::OK;
1174}
1175
Risan8c9f3322018-10-29 08:52:56 +09001176int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1177 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001178 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001179 std::string* outVolId) {
1180 dev_t stubId = --mNextStubId;
1181 auto vol = std::shared_ptr<android::vold::StubVolume>(
1182 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001183
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001184 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001185 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1186 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001187 if (flags & android::vold::Disk::Flags::kStubVisible) {
1188 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1189 } else {
1190 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1191 }
Risan82e90de2020-02-04 16:07:21 +09001192 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001193 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001194 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001195 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001196 disk->initializePartition(vol);
1197 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001198 *outVolId = vol->getId();
1199 return android::OK;
1200}
1201
1202int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001203 auto tokens = android::base::Split(volId, ":");
1204 CHECK(tokens.size() == 2);
1205 dev_t stubId;
1206 CHECK(android::base::ParseUint(tokens[1], &stubId));
1207 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001208 return android::OK;
1209}
1210
Risan8f6198d2018-10-26 20:56:45 -06001211int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001212 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001213}
1214
Risan8f6198d2018-10-26 20:56:45 -06001215int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001216 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001217}
1218
1219int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001220 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001221}
Paul Lawrenced73dfd42023-08-11 10:27:24 -07001222
1223android::status_t android::vold::GetStorageSize(int64_t* storageSize) {
1224 // Start with the /data mount point from fs_mgr
1225 auto entry = android::fs_mgr::GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
1226 if (entry == nullptr) {
1227 LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
1228 return EINVAL;
1229 }
1230
1231 // Follow any symbolic links
1232 std::string blkDevice = entry->blk_device;
1233 std::string dataDevice;
1234 if (!android::base::Realpath(blkDevice, &dataDevice)) {
1235 dataDevice = blkDevice;
1236 }
1237
1238 // Handle mapped volumes.
1239 auto& dm = android::dm::DeviceMapper::Instance();
1240 for (;;) {
1241 auto parent = dm.GetParentBlockDeviceByPath(dataDevice);
1242 if (!parent.has_value()) break;
1243 dataDevice = *parent;
1244 }
1245
1246 // Get the potential /sys/block entry
1247 std::size_t leaf = dataDevice.rfind('/');
1248 if (leaf == std::string::npos) {
1249 LOG(ERROR) << "data device " << dataDevice << " is not a path";
1250 return EINVAL;
1251 }
1252 if (dataDevice.substr(0, leaf) != "/dev/block") {
1253 LOG(ERROR) << "data device " << dataDevice << " is not a block device";
1254 return EINVAL;
1255 }
1256 std::string sysfs = std::string() + "/sys/block/" + dataDevice.substr(leaf + 1);
1257
1258 // Look for a directory in /sys/block containing size where the name is a shortened
1259 // version of the name we now have
1260 // Typically we start with something like /sys/block/sda2, and we want /sys/block/sda
1261 // Note that this directory only contains actual disks, not partitions, so this is
1262 // not going to find anything other than the disks
1263 std::string size;
1264 std::string sizeFile;
1265 for (std::string sysfsDir = sysfs;; sysfsDir = sysfsDir.substr(0, sysfsDir.size() - 1)) {
1266 if (sysfsDir.back() == '/') {
1267 LOG(ERROR) << "Could not find valid block device from " << sysfs;
1268 return EINVAL;
1269 }
1270 sizeFile = sysfsDir + "/size";
1271 if (android::base::ReadFileToString(sizeFile, &size, true)) {
1272 break;
1273 }
1274 }
1275
1276 // Read the size file and be done
1277 std::stringstream ssSize(size);
1278 ssSize >> *storageSize;
1279 if (ssSize.fail()) {
1280 LOG(ERROR) << sizeFile << " cannot be read as an integer";
1281 return EINVAL;
1282 }
1283
1284 *storageSize *= 512;
1285 return OK;
1286}