blob: f97397d54537f3ec20c741ec2700329c70891317 [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
Jiyong Park8d21c922019-01-04 13:35:25 +090038#include <ApexProperties.sysprop.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 Crowleyc6433a22017-10-24 14:54:43 -070056
Risanac02a482018-10-31 21:59:47 -060057#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070058#include "Devmapper.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"
Risan8c9f3322018-10-29 08:52:56 +090072#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080073
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000074using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070075using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070076using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070077using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070078using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060079using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080080using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000081using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080082using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080083using android::vold::DeleteDirContentsAndDir;
Ricky Wai07e64a42020-02-11 14:31:24 +000084using android::vold::EnsureDirExists;
Martijn Coenen62a4b272020-01-31 15:23:09 +010085using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070086using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070087using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010088using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010089using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010090using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080091using android::vold::Symlink;
92using android::vold::Unlink;
93using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080094using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010095using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070096
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060097static const char* kPathUserMount = "/mnt/user";
98static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
99
100static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
101
Sudheer Shanka53947a32018-08-01 10:24:13 -0700102static const std::string kEmptyString("");
103
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600104/* 512MiB is large enough for testing purposes */
105static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700106
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700107static const unsigned int kMajorBlockMmc = 179;
108
Ricky Wai07e64a42020-02-11 14:31:24 +0000109using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
110
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700111VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700112
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700113VolumeManager* VolumeManager::Instance() {
114 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700115 return sInstance;
116}
117
118VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800119 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600120 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900121 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700122 // For security reasons, assume that a secure keyguard is
123 // showing until we hear otherwise
124 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700125}
126
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700127VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800128
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600130 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700131 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600132 if (access(kPathVirtualDisk, F_OK) != 0) {
133 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
134 }
135
136 if (mVirtualDisk == nullptr) {
137 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
138 LOG(ERROR) << "Failed to create virtual disk";
139 return -1;
140 }
141
142 struct stat buf;
143 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
144 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
145 return -1;
146 }
147
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700148 auto disk = new android::vold::Disk(
149 "virtual", buf.st_rdev, "virtual",
150 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600151 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700152 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600153 }
154 } else {
155 if (mVirtualDisk != nullptr) {
156 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700157 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600158
159 Loop::destroyByDevice(mVirtualDiskPath.c_str());
160 mVirtualDisk = nullptr;
161 }
162
163 if (access(kPathVirtualDisk, F_OK) == 0) {
164 unlink(kPathVirtualDisk);
165 }
166 }
167 return 0;
168}
169
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700170int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800171 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700172 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800173}
174
San Mehatf1b736b2009-10-10 17:22:08 -0700175int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600176 ATRACE_NAME("VolumeManager::start");
177
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700178 // Always start from a clean slate by unmounting everything in
179 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700180 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700181
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600182 Devmapper::destroyAll();
183 Loop::destroyAll();
184
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700185 // Assume that we always have an emulated volume on internal
186 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100187 CHECK(mInternalEmulatedVolumes.empty());
188
189 auto vol = std::shared_ptr<android::vold::VolumeBase>(
190 new android::vold::EmulatedVolume("/data/media", 0));
191 vol->setMountUserId(0);
192 vol->create();
193 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600195 // Consider creating a virtual disk
196 updateVirtualDisk();
197
San Mehatf1b736b2009-10-10 17:22:08 -0700198 return 0;
199}
200
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700201void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700202 std::lock_guard<std::mutex> lock(mLock);
203
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700204 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700205 LOG(DEBUG) << "----------------";
206 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700207 evt->dump();
208 }
San Mehatf1b736b2009-10-10 17:22:08 -0700209
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700210 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
211 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700212
213 if (devType != "disk") return;
214
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600215 int major = std::stoi(evt->findParam("MAJOR"));
216 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700217 dev_t device = makedev(major, minor);
218
219 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700220 case NetlinkEvent::Action::kAdd: {
221 for (const auto& source : mDiskSources) {
222 if (source->matches(eventPath)) {
223 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700224 // specific to virtual platforms; see Utils.cpp for details)
225 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700226 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700227 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700228 flags |= android::vold::Disk::Flags::kSd;
229 } else {
230 flags |= android::vold::Disk::Flags::kUsb;
231 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700232
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700233 auto disk =
234 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
235 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
236 break;
237 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700239 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700240 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700241 case NetlinkEvent::Action::kChange: {
242 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
243 handleDiskChanged(device);
244 break;
245 }
246 case NetlinkEvent::Action::kRemove: {
247 handleDiskRemoved(device);
248 break;
249 }
250 default: {
251 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
252 break;
253 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700254 }
255}
256
Jeff Sharkey401b2602017-12-14 22:15:20 -0700257void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
258 // For security reasons, if secure keyguard is showing, wait
259 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100260 // Additionally, wait until user 0 is actually started, since we need
261 // the user to be up before we can mount a FUSE daemon to handle the disk.
262 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700263 if (mSecureKeyguardShowing) {
264 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700265 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700266 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100267 } else if (!userZeroStarted) {
268 LOG(INFO) << "Found disk at " << disk->getEventPath()
269 << " but delaying scan due to user zero not having started";
270 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700271 } else {
272 disk->create();
273 mDisks.push_back(disk);
274 }
275}
276
277void VolumeManager::handleDiskChanged(dev_t device) {
278 for (const auto& disk : mDisks) {
279 if (disk->getDevice() == device) {
280 disk->readMetadata();
281 disk->readPartitions();
282 }
283 }
284
285 // For security reasons, we ignore all pending disks, since
286 // we'll scan them once the device is unlocked
287}
288
289void VolumeManager::handleDiskRemoved(dev_t device) {
290 auto i = mDisks.begin();
291 while (i != mDisks.end()) {
292 if ((*i)->getDevice() == device) {
293 (*i)->destroy();
294 i = mDisks.erase(i);
295 } else {
296 ++i;
297 }
298 }
299 auto j = mPendingDisks.begin();
300 while (j != mPendingDisks.end()) {
301 if ((*j)->getDevice() == device) {
302 j = mPendingDisks.erase(j);
303 } else {
304 ++j;
305 }
306 }
307}
308
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700309void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800310 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700311 mDiskSources.push_back(diskSource);
312}
313
314std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
315 for (auto disk : mDisks) {
316 if (disk->getId() == id) {
317 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700318 }
319 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700320 return nullptr;
321}
San Mehatf1b736b2009-10-10 17:22:08 -0700322
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700323std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100324 for (const auto& vol : mInternalEmulatedVolumes) {
325 if (vol->getId() == id) {
326 return vol;
327 }
San Mehatf1b736b2009-10-10 17:22:08 -0700328 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700329 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700330 auto vol = disk->findVolume(id);
331 if (vol != nullptr) {
332 return vol;
333 }
334 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600335 for (const auto& vol : mObbVolumes) {
336 if (vol->getId() == id) {
337 return vol;
338 }
339 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700340 return nullptr;
341}
342
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800343void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
344 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700345 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700346 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700347 disk->listVolumes(type, list);
348 }
349}
350
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600351int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700352 std::string normalizedGuid;
353 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
354 LOG(WARNING) << "Invalid GUID " << partGuid;
355 return -1;
356 }
357
Paul Crowleyc6433a22017-10-24 14:54:43 -0700358 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700359 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
360 if (unlink(keyPath.c_str()) != 0) {
361 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700362 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700363 }
Eric Biggersa701c452018-10-23 13:06:55 -0700364 if (fscrypt_is_native()) {
365 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700366 success = false;
367 }
368 }
369 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700370}
371
Zima438b242019-09-25 14:37:38 +0100372void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
373 // Destroy and remove all unstacked EmulatedVolumes for the user
374 auto i = mInternalEmulatedVolumes.begin();
375 while (i != mInternalEmulatedVolumes.end()) {
376 auto vol = *i;
377 if (vol->getMountUserId() == userId) {
378 vol->destroy();
379 i = mInternalEmulatedVolumes.erase(i);
380 } else {
381 i++;
382 }
383 }
384
385 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
386 std::list<std::string> private_vols;
387 listVolumes(VolumeBase::Type::kPrivate, private_vols);
388 for (const std::string& id : private_vols) {
389 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
390 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
391 if (pvol->getState() == VolumeBase::State::kMounted) {
392 for (const auto& vol : pvol->getVolumes()) {
393 if (vol->getMountUserId() == userId) {
394 vols_to_remove.push_back(vol);
395 }
396 }
397 for (const auto& vol : vols_to_remove) {
398 vol->destroy();
399 pvol->removeVolume(vol);
400 }
401 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
402 }
403}
404
405void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
406 // Create unstacked EmulatedVolumes for the user
407 auto vol = std::shared_ptr<android::vold::VolumeBase>(
408 new android::vold::EmulatedVolume("/data/media", userId));
409 vol->setMountUserId(userId);
410 mInternalEmulatedVolumes.push_back(vol);
411 vol->create();
412
413 // Create stacked EmulatedVolumes for the user on each PrivateVolume
414 std::list<std::string> private_vols;
415 listVolumes(VolumeBase::Type::kPrivate, private_vols);
416 for (const std::string& id : private_vols) {
417 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
418 if (pvol->getState() == VolumeBase::State::kMounted) {
419 auto evol =
420 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
421 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
422 userId));
423 evol->setMountUserId(userId);
424 pvol->addVolume(evol);
425 evol->create();
426 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
427 }
428}
429
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700430int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100431 LOG(INFO) << "onUserAdded: " << userId;
432
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700433 mAddedUsers[userId] = userSerialNumber;
434 return 0;
435}
436
437int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100438 LOG(INFO) << "onUserRemoved: " << userId;
439
Zim2d45d9b2019-11-14 16:19:05 +0000440 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700441 mAddedUsers.erase(userId);
442 return 0;
443}
444
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700445int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100446 LOG(INFO) << "onUserStarted: " << userId;
447
Zim2d45d9b2019-11-14 16:19:05 +0000448 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
449 createEmulatedVolumesForUser(userId);
450 }
451
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700452 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100453
454 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700455 return 0;
456}
457
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700458int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700459 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100460
Zim2d45d9b2019-11-14 16:19:05 +0000461 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100462 destroyEmulatedVolumesForUser(userId);
463 }
464
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700465 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700466 return 0;
467}
468
Martijn Coenencf5916f2020-01-03 14:36:45 +0100469void VolumeManager::createPendingDisksIfNeeded() {
470 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
471 if (!mSecureKeyguardShowing && userZeroStarted) {
472 // Now that secure keyguard has been dismissed and user 0 has
473 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700474 for (const auto& disk : mPendingDisks) {
475 disk->create();
476 mDisks.push_back(disk);
477 }
478 mPendingDisks.clear();
479 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100480}
481
482int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
483 mSecureKeyguardShowing = isShowing;
484 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700485 return 0;
486}
487
Narayan Kamath02efdf52019-11-27 10:53:51 +0000488// This code is executed after a fork so it's very important that the set of
489// methods we call here is strictly limited.
490//
491// TODO: Get rid of this guesswork altogether and instead exec a process
492// immediately after fork to do our bindding for us.
493static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000494 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000495 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000496 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000497 strerror(errno));
498 return false;
499 }
500
501 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
502 // to also protect against future changes that may cause issues across a
503 // fork.
504 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
505 errno != ENOENT) {
506 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
507 strerror(errno));
508 return false;
509 }
510
511 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
512 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000513 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000514 return false;
515 }
516
517 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
518 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000519 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000520 strerror(errno));
521 return false;
522 }
523
524 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
525 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000526 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000527 return false;
528 }
529
530 return true;
531}
532
Ricky Wai07e64a42020-02-11 14:31:24 +0000533// Fork the process and remount storage
534bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
535 int32_t mountMode = *static_cast<int32_t*>(params);
536 std::string userSource;
537 std::string storageSource;
538 pid_t child;
539 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800540 switch (mountMode) {
541 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000542 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800543 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000544 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800545 break;
546 case VoldNativeService::REMOUNT_MODE_READ:
Ricky Wai07e64a42020-02-11 14:31:24 +0000547 storageSource = "/mnt/runtime/read";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800548 break;
549 case VoldNativeService::REMOUNT_MODE_WRITE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700550 case VoldNativeService::REMOUNT_MODE_LEGACY:
551 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000552 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800553 break;
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700554 case VoldNativeService::REMOUNT_MODE_FULL:
Ricky Wai07e64a42020-02-11 14:31:24 +0000555 storageSource = "/mnt/runtime/full";
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700556 break;
Zim981222f2019-09-09 10:24:44 +0100557 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000558 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800559 default:
560 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000561 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800562 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000563 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700564
Ricky Wai07e64a42020-02-11 14:31:24 +0000565 // Fork a child to mount user-specific symlink helper into place
566 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
567 if (!(child = fork())) {
568 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
569 _exit(0);
570 } else {
571 _exit(1);
572 }
573 }
574
575 if (child == -1) {
576 PLOG(ERROR) << "Failed to fork";
577 return false;
578 } else {
579 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
580 }
581 return true;
582}
583
584// Helper function to scan all processes in /proc and call the callback if:
585// 1). pid belongs to an app process
586// 2). If input uid is 0 or it matches the process uid
587// 3). If userId is not -1 or userId matches the process userId
588bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700589 DIR* dir;
590 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600591 std::string rootName;
592 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700593 int pidFd;
594 int nsFd;
595 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700596
Jiyong Park8d21c922019-01-04 13:35:25 +0900597 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
598
Jeff Sharkey66270a22015-06-24 11:49:24 -0700599 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000600 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
601 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700602 }
603
604 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600605 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000606 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700607 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000608 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700609 }
610
Ricky Wai07e64a42020-02-11 14:31:24 +0000611 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700612 // Poke through all running PIDs look for apps running as UID
613 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700614 pid_t pid;
615 if (de->d_type != DT_DIR) continue;
616 if (!android::base::ParseInt(de->d_name, &pid)) continue;
617
Jeff Sharkey66270a22015-06-24 11:49:24 -0700618 pidFd = -1;
619 nsFd = -1;
620
621 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
622 if (pidFd < 0) {
623 goto next;
624 }
625 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000626 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700627 goto next;
628 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000629 if (uid != 0 && sb.st_uid != uid) {
630 goto next;
631 }
632 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700633 goto next;
634 }
635
636 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600637 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000638 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
639 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700640 goto next;
641 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600642 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700643 goto next;
644 }
645
Jiyong Park8d21c922019-01-04 13:35:25 +0900646 if (apexUpdatable) {
647 std::string exeName;
648 // When ro.apex.bionic_updatable is set to true,
649 // some early native processes have mount namespaces that are different
650 // from that of the init. Therefore, above check can't filter them out.
651 // Since the propagation type of / is 'shared', unmounting /storage
652 // for the early native processes affects other processes including
653 // init. Filter out such processes by skipping if a process is a
654 // non-Java process whose UID is < AID_APP_START. (The UID condition
655 // is required to not filter out child processes spawned by apps.)
656 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900657 goto next;
658 }
659 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900660 goto next;
661 }
662 }
663
Jeff Sharkey66270a22015-06-24 11:49:24 -0700664 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700665 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
666 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700667 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000668 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
669 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700670 goto next;
671 }
672
Ricky Wai07e64a42020-02-11 14:31:24 +0000673 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
674 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700675 }
676
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700677 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700678 close(nsFd);
679 close(pidFd);
680 }
681 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000682 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
683 return true;
684}
685
Ricky Waia2ca11e2021-01-15 14:03:23 +0000686// In each app's namespace, unmount obb and data dirs
687static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
688 int uid, const char* targets[], int size) {
689 // This code is executed after a fork so it's very important that the set of
690 // methods we call here is strictly limited.
691 if (setns(nsFd, CLONE_NEWNS) != 0) {
692 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
693 return false;
694 }
695
696 // Unmount of Android/data/foo needs to be done before Android/data below.
697 bool result = true;
698 for (int i = 0; i < size; i++) {
699 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
700 errno != ENOENT) {
701 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
702 targets[i], strerror(errno));
703 result = false;
704 }
705 }
706
707 // Mount tmpfs on Android/data and Android/obb
708 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
709 errno != ENOENT) {
710 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
711 android_data_dir, strerror(errno));
712 result = false;
713 }
714 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
715 errno != ENOENT) {
716 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
717 android_obb_dir, strerror(errno));
718 result = false;
719 }
720 return result;
721}
722
Ricky Waie96b34f2020-05-07 16:01:33 +0100723// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
724// package dirs.
725static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
726 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000727 // This code is executed after a fork so it's very important that the set of
728 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000729 if (setns(nsFd, CLONE_NEWNS) != 0) {
730 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
731 return false;
732 }
733
Ricky Waie96b34f2020-05-07 16:01:33 +0100734 // Mount tmpfs on Android/data and Android/obb
735 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
736 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
737 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
738 android_data_dir, strerror(errno));
739 return false;
740 }
741 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
742 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
743 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
744 android_obb_dir, strerror(errno));
745 return false;
746 }
747
Ricky Wai6b122572020-02-28 16:30:47 +0000748 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100749 // Create package dir and bind mount it to the actual one.
750 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
751 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
752 targets[i], strerror(errno));
753 return false;
754 }
Ricky Wai6b122572020-02-28 16:30:47 +0000755 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
756 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
757 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000758 return false;
759 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000760 }
761 return true;
762}
763
Ricky Wai6b122572020-02-28 16:30:47 +0000764static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
765 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700766 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000767 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
768 userId, dirName.c_str(), packageName.c_str());
769 } else {
770 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
771 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000772 }
Ricky Wai6b122572020-02-28 16:30:47 +0000773}
774
775static std::string getStorageDirTarget(userid_t userId, std::string dirName,
776 std::string packageName) {
777 return StringPrintf("/storage/emulated/%d/%s/%s",
778 userId, dirName.c_str(), packageName.c_str());
779}
780
Ricky Waia2ca11e2021-01-15 14:03:23 +0000781// Fork the process and remount / unmount app data and obb dirs
782bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000783 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000784 userid_t userId = multiuser_get_user_id(uid);
785 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
786 android::base::unique_fd nsFd(
787 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
788 if (nsFd == -1) {
789 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
790 return false;
791 }
792 // Storing both Android/obb and Android/data paths.
793 int size = packageNames.size() * 2;
794
795 std::unique_ptr<std::string[]> sources(new std::string[size]);
796 std::unique_ptr<std::string[]> targets(new std::string[size]);
797 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
798 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
799 const char** sources_cstr = sources_uptr.get();
800 const char** targets_cstr = targets_uptr.get();
801
802 for (int i = 0; i < size; i += 2) {
803 std::string const& packageName = packageNames[i/2];
804 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
805 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
806 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
807 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
808
809 sources_cstr[i] = sources[i].c_str();
810 targets_cstr[i] = targets[i].c_str();
811 sources_cstr[i+1] = sources[i+1].c_str();
812 targets_cstr[i+1] = targets[i+1].c_str();
813 }
814
815 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000816 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000817 // This needs to be done before EnsureDirExists to ensure Android/ is created.
818 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000819 if (status != OK) {
820 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
821 return false;
822 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000823 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
824 if (status != OK) {
825 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
826 return false;
827 }
Ricky Wai6b122572020-02-28 16:30:47 +0000828 }
829
Ricky Waie96b34f2020-05-07 16:01:33 +0100830 char android_data_dir[PATH_MAX];
831 char android_obb_dir[PATH_MAX];
832 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
833 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
834
Ricky Wai6b122572020-02-28 16:30:47 +0000835 pid_t child;
836 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
837 // original vold process mount namespace.
838 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000839 if (doUnmount) {
840 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
841 targets_cstr, size)) {
842 _exit(0);
843 } else {
844 _exit(1);
845 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000846 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000847 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
848 sources_cstr, targets_cstr, size)) {
849 _exit(0);
850 } else {
851 _exit(1);
852 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000853 }
854 }
Ricky Wai6b122572020-02-28 16:30:47 +0000855
Ricky Wai07e64a42020-02-11 14:31:24 +0000856 if (child == -1) {
857 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000858 return false;
859 } else {
860 int status;
861 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
862 PLOG(ERROR) << "Failed to waitpid: " << child;
863 return false;
864 }
865 if (!WIFEXITED(status)) {
866 PLOG(ERROR) << "Process did not exit normally, status: " << status;
867 return false;
868 }
869 if (WEXITSTATUS(status)) {
870 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
871 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000872 }
873 }
Ricky Wai6b122572020-02-28 16:30:47 +0000874 return true;
875}
876
Ricky Waia2ca11e2021-01-15 14:03:23 +0000877int VolumeManager::handleAppStorageDirs(int uid, int pid,
878 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000879 // Only run the remount if fuse is mounted for that user.
880 userid_t userId = multiuser_get_user_id(uid);
881 bool fuseMounted = false;
882 for (auto& vol : mInternalEmulatedVolumes) {
883 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
884 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
885 if (emulatedVol) {
886 fuseMounted = emulatedVol->isFuseMounted();
887 }
888 break;
889 }
890 }
891 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000892 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000893 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700894 return 0;
895}
896
Martijn Coenen23c04452020-04-29 07:49:41 +0200897int VolumeManager::abortFuse() {
898 return android::vold::AbortFuseConnections();
899}
900
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700901int VolumeManager::reset() {
902 // Tear down all existing disks/volumes and start from a blank slate so
903 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100904 for (const auto& vol : mInternalEmulatedVolumes) {
905 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800906 }
Zima438b242019-09-25 14:37:38 +0100907 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100908
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700909 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700910 disk->destroy();
911 disk->create();
912 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600913 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700914 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800915 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700916 return 0;
917}
918
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700919// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700920int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100921 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700922 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700923 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700924 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100925 for (const auto& vol : mInternalEmulatedVolumes) {
926 vol->destroy();
927 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700928 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700929 disk->destroy();
930 }
Zima438b242019-09-25 14:37:38 +0100931
932 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700933 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700934 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700935 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200936
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700937 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700938}
939
Jeff Sharkey9c484982015-03-31 10:35:33 -0700940int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700941 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600942 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700943
Jeff Sharkey9c484982015-03-31 10:35:33 -0700944 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100945 for (const auto& vol : mInternalEmulatedVolumes) {
946 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700947 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700948 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700949 disk->unmountAll();
950 }
951
952 // Worst case we might have some stale mounts lurking around, so
953 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800954 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700955 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600956 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700957 return -errno;
958 }
959
960 // Some volumes can be stacked on each other, so force unmount in
961 // reverse order to give us the best chance of success.
962 std::list<std::string> toUnmount;
963 mntent* mentry;
964 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600965 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700966 if ((StartsWith(test, "/mnt/") &&
967#ifdef __ANDROID_DEBUGGABLE__
968 !StartsWith(test, "/mnt/scratch") &&
969#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100970 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100971 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700972 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600973 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700974 }
975 }
976 endmntent(fp);
977
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700978 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600979 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700980 android::vold::ForceUnmount(path);
981 }
982
983 return 0;
984}
985
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000986int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000987 int size = paths.size();
988 for (int i = 0; i < size; i++) {
989 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
990 true /* skipIfDirExists */);
991 if (result != OK) {
992 return result;
993 }
994 }
995 return OK;
996}
997
998int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
999 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001000 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001001 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001002 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001003 return -EINVAL;
1004 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001005
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001006 // Find the volume it belongs to
1007 auto filter_fn = [&](const VolumeBase& vol) {
1008 if (vol.getState() != VolumeBase::State::kMounted) {
1009 // The volume must be mounted
1010 return false;
1011 }
1012 if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
1013 // and visible
1014 return false;
1015 }
1016 if (vol.getInternalPath().empty()) {
1017 return false;
1018 }
1019 if (vol.getMountUserId() != USER_UNKNOWN &&
1020 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1021 // The app dir must be created on a volume with the same user-id
1022 return false;
1023 }
1024 if (!path.empty() && StartsWith(path, vol.getPath())) {
1025 return true;
1026 }
1027
1028 return false;
1029 };
1030 auto volume = findVolumeWithFilter(filter_fn);
1031 if (volume == nullptr) {
1032 LOG(ERROR) << "Failed to find mounted volume for " << path;
1033 return -EINVAL;
1034 }
Zimc59d7742020-01-06 21:48:16 +00001035 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1036 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1037 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1038 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001039 const std::string lowerPath =
1040 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001041
Martijn Coenen62a4b272020-01-31 15:23:09 +01001042 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1043
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001044 const int access_result = access(lowerPath.c_str(), F_OK);
1045 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001046 // Nothing to fixup
1047 return OK;
1048 }
1049
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001050 if (skipIfDirExists && access_result == 0) {
1051 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1052 // which the dir doesn't need to have correct permission for now yet.
1053 return OK;
1054 }
1055
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001056 if (volume->getType() == VolumeBase::Type::kPublic) {
1057 // On public volumes, we don't need to setup permissions, as everything goes through
1058 // FUSE; just create the dirs and be done with it.
1059 return fs_mkdirs(lowerPath.c_str(), 0700);
1060 }
1061
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001062 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001063 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1064}
1065
1066int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001067 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001068 //sdcardfs magically does this for us
1069 return OK;
1070 }
1071 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001072}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001073
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001074int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001075 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001076 int id = mNextObbId++;
1077
Martijn Coenend6a612a2020-11-19 10:49:45 +01001078 std::string lowerSourcePath;
1079
1080 // Convert to lower filesystem path
1081 if (StartsWith(sourcePath, "/storage/")) {
1082 auto filter_fn = [&](const VolumeBase& vol) {
1083 if (vol.getState() != VolumeBase::State::kMounted) {
1084 // The volume must be mounted
1085 return false;
1086 }
1087 if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
1088 // and visible
1089 return false;
1090 }
1091 if (vol.getInternalPath().empty()) {
1092 return false;
1093 }
1094 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1095 return true;
1096 }
1097
1098 return false;
1099 };
1100 auto volume = findVolumeWithFilter(filter_fn);
1101 if (volume == nullptr) {
1102 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1103 return -EINVAL;
1104 } else {
1105 lowerSourcePath =
1106 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1107 }
1108 } else {
1109 lowerSourcePath = sourcePath;
1110 }
1111
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001112 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Martijn Coenend6a612a2020-11-19 10:49:45 +01001113 new android::vold::ObbVolume(id, lowerSourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001114 vol->create();
1115
1116 mObbVolumes.push_back(vol);
1117 *outVolId = vol->getId();
1118 return android::OK;
1119}
1120
1121int VolumeManager::destroyObb(const std::string& volId) {
1122 auto i = mObbVolumes.begin();
1123 while (i != mObbVolumes.end()) {
1124 if ((*i)->getId() == volId) {
1125 (*i)->destroy();
1126 i = mObbVolumes.erase(i);
1127 } else {
1128 ++i;
1129 }
1130 }
1131 return android::OK;
1132}
1133
Risan8c9f3322018-10-29 08:52:56 +09001134int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1135 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001136 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001137 std::string* outVolId) {
1138 dev_t stubId = --mNextStubId;
1139 auto vol = std::shared_ptr<android::vold::StubVolume>(
1140 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001141
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001142 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001143 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1144 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001145 if (flags & android::vold::Disk::Flags::kStubVisible) {
1146 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1147 } else {
1148 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1149 }
Risan82e90de2020-02-04 16:07:21 +09001150 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001151 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001152 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001153 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001154 disk->initializePartition(vol);
1155 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001156 *outVolId = vol->getId();
1157 return android::OK;
1158}
1159
1160int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001161 auto tokens = android::base::Split(volId, ":");
1162 CHECK(tokens.size() == 2);
1163 dev_t stubId;
1164 CHECK(android::base::ParseUint(tokens[1], &stubId));
1165 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001166 return android::OK;
1167}
1168
Risan8f6198d2018-10-26 20:56:45 -06001169int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001170 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001171}
1172
Risan8f6198d2018-10-26 20:56:45 -06001173int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001174 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001175}
1176
1177int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001178 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001179}