blob: bc51042a6849d1d6c3d02497fa0d416b1a2d2310 [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"
Eric Biggersa701c452018-10-23 13:06:55 -070058#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080059#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070060#include "NetlinkManager.h"
61#include "Process.h"
62#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070063#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070064#include "VoldUtil.h"
65#include "VolumeManager.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070066#include "fs/Ext4.h"
67#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070068#include "model/EmulatedVolume.h"
69#include "model/ObbVolume.h"
Zima438b242019-09-25 14:37:38 +010070#include "model/PrivateVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090071#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080072
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000073using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070074using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070075using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070076using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070077using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060078using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080079using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000080using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080081using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080082using android::vold::DeleteDirContentsAndDir;
Ricky Wai07e64a42020-02-11 14:31:24 +000083using android::vold::EnsureDirExists;
Martijn Coenen62a4b272020-01-31 15:23:09 +010084using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070085using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070086using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010087using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010088using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010089using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080090using android::vold::Symlink;
91using android::vold::Unlink;
92using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080093using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010094using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070095
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060096static const char* kPathUserMount = "/mnt/user";
97static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
98
99static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
100
Sudheer Shanka53947a32018-08-01 10:24:13 -0700101static const std::string kEmptyString("");
102
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600103/* 512MiB is large enough for testing purposes */
104static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700105
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700106static const unsigned int kMajorBlockMmc = 179;
107
Ricky Wai07e64a42020-02-11 14:31:24 +0000108using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
109
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700110VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700111
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700112VolumeManager* VolumeManager::Instance() {
113 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700114 return sInstance;
115}
116
117VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800118 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600119 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900120 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700121 // For security reasons, assume that a secure keyguard is
122 // showing until we hear otherwise
123 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700124}
125
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700126VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800127
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600128int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600129 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700130 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600131 if (access(kPathVirtualDisk, F_OK) != 0) {
132 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
133 }
134
135 if (mVirtualDisk == nullptr) {
136 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
137 LOG(ERROR) << "Failed to create virtual disk";
138 return -1;
139 }
140
141 struct stat buf;
142 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
143 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
144 return -1;
145 }
146
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700147 auto disk = new android::vold::Disk(
148 "virtual", buf.st_rdev, "virtual",
149 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600150 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700151 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600152 }
153 } else {
154 if (mVirtualDisk != nullptr) {
155 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700156 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600157
158 Loop::destroyByDevice(mVirtualDiskPath.c_str());
159 mVirtualDisk = nullptr;
160 }
161
162 if (access(kPathVirtualDisk, F_OK) == 0) {
163 unlink(kPathVirtualDisk);
164 }
165 }
166 return 0;
167}
168
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700169int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800170 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700171 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800172}
173
San Mehatf1b736b2009-10-10 17:22:08 -0700174int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600175 ATRACE_NAME("VolumeManager::start");
176
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 // Always start from a clean slate by unmounting everything in
178 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700179 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700180
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600181 Loop::destroyAll();
182
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700183 // Assume that we always have an emulated volume on internal
184 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100185 CHECK(mInternalEmulatedVolumes.empty());
186
187 auto vol = std::shared_ptr<android::vold::VolumeBase>(
188 new android::vold::EmulatedVolume("/data/media", 0));
189 vol->setMountUserId(0);
190 vol->create();
191 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600193 // Consider creating a virtual disk
194 updateVirtualDisk();
195
San Mehatf1b736b2009-10-10 17:22:08 -0700196 return 0;
197}
198
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700199void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700200 std::lock_guard<std::mutex> lock(mLock);
201
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700202 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700203 LOG(DEBUG) << "----------------";
204 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700205 evt->dump();
206 }
San Mehatf1b736b2009-10-10 17:22:08 -0700207
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700208 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
209 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700210
211 if (devType != "disk") return;
212
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600213 int major = std::stoi(evt->findParam("MAJOR"));
214 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700215 dev_t device = makedev(major, minor);
216
217 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700218 case NetlinkEvent::Action::kAdd: {
219 for (const auto& source : mDiskSources) {
220 if (source->matches(eventPath)) {
221 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700222 // specific to virtual platforms; see Utils.cpp for details)
223 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700224 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700225 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700226 flags |= android::vold::Disk::Flags::kSd;
227 } else {
228 flags |= android::vold::Disk::Flags::kUsb;
229 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700230
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700231 auto disk =
232 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
233 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
234 break;
235 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700236 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700237 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700239 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100240 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700241 handleDiskChanged(device);
242 break;
243 }
244 case NetlinkEvent::Action::kRemove: {
245 handleDiskRemoved(device);
246 break;
247 }
248 default: {
249 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
250 break;
251 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700252 }
253}
254
Jeff Sharkey401b2602017-12-14 22:15:20 -0700255void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
256 // For security reasons, if secure keyguard is showing, wait
257 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100258 // Additionally, wait until user 0 is actually started, since we need
259 // the user to be up before we can mount a FUSE daemon to handle the disk.
260 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700261 if (mSecureKeyguardShowing) {
262 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700263 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700264 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100265 } else if (!userZeroStarted) {
266 LOG(INFO) << "Found disk at " << disk->getEventPath()
267 << " but delaying scan due to user zero not having started";
268 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700269 } else {
270 disk->create();
271 mDisks.push_back(disk);
272 }
273}
274
275void VolumeManager::handleDiskChanged(dev_t device) {
276 for (const auto& disk : mDisks) {
277 if (disk->getDevice() == device) {
278 disk->readMetadata();
279 disk->readPartitions();
280 }
281 }
282
283 // For security reasons, we ignore all pending disks, since
284 // we'll scan them once the device is unlocked
285}
286
287void VolumeManager::handleDiskRemoved(dev_t device) {
288 auto i = mDisks.begin();
289 while (i != mDisks.end()) {
290 if ((*i)->getDevice() == device) {
291 (*i)->destroy();
292 i = mDisks.erase(i);
293 } else {
294 ++i;
295 }
296 }
297 auto j = mPendingDisks.begin();
298 while (j != mPendingDisks.end()) {
299 if ((*j)->getDevice() == device) {
300 j = mPendingDisks.erase(j);
301 } else {
302 ++j;
303 }
304 }
305}
306
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700307void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800308 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700309 mDiskSources.push_back(diskSource);
310}
311
312std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
313 for (auto disk : mDisks) {
314 if (disk->getId() == id) {
315 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700316 }
317 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318 return nullptr;
319}
San Mehatf1b736b2009-10-10 17:22:08 -0700320
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100322 for (const auto& vol : mInternalEmulatedVolumes) {
323 if (vol->getId() == id) {
324 return vol;
325 }
San Mehatf1b736b2009-10-10 17:22:08 -0700326 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700327 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700328 auto vol = disk->findVolume(id);
329 if (vol != nullptr) {
330 return vol;
331 }
332 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600333 for (const auto& vol : mObbVolumes) {
334 if (vol->getId() == id) {
335 return vol;
336 }
337 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700338 return nullptr;
339}
340
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800341void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
342 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700343 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700344 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700345 disk->listVolumes(type, list);
346 }
347}
348
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600349int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700350 std::string normalizedGuid;
351 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
352 LOG(WARNING) << "Invalid GUID " << partGuid;
353 return -1;
354 }
355
Paul Crowleyc6433a22017-10-24 14:54:43 -0700356 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700357 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
358 if (unlink(keyPath.c_str()) != 0) {
359 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700360 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700361 }
Eric Biggersa701c452018-10-23 13:06:55 -0700362 if (fscrypt_is_native()) {
363 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700364 success = false;
365 }
366 }
367 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700368}
369
Zima438b242019-09-25 14:37:38 +0100370void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
371 // Destroy and remove all unstacked EmulatedVolumes for the user
372 auto i = mInternalEmulatedVolumes.begin();
373 while (i != mInternalEmulatedVolumes.end()) {
374 auto vol = *i;
375 if (vol->getMountUserId() == userId) {
376 vol->destroy();
377 i = mInternalEmulatedVolumes.erase(i);
378 } else {
379 i++;
380 }
381 }
382
383 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
384 std::list<std::string> private_vols;
385 listVolumes(VolumeBase::Type::kPrivate, private_vols);
386 for (const std::string& id : private_vols) {
387 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
388 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
389 if (pvol->getState() == VolumeBase::State::kMounted) {
390 for (const auto& vol : pvol->getVolumes()) {
391 if (vol->getMountUserId() == userId) {
392 vols_to_remove.push_back(vol);
393 }
394 }
395 for (const auto& vol : vols_to_remove) {
396 vol->destroy();
397 pvol->removeVolume(vol);
398 }
399 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
400 }
401}
402
403void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
404 // Create unstacked EmulatedVolumes for the user
405 auto vol = std::shared_ptr<android::vold::VolumeBase>(
406 new android::vold::EmulatedVolume("/data/media", userId));
407 vol->setMountUserId(userId);
408 mInternalEmulatedVolumes.push_back(vol);
409 vol->create();
410
411 // Create stacked EmulatedVolumes for the user on each PrivateVolume
412 std::list<std::string> private_vols;
413 listVolumes(VolumeBase::Type::kPrivate, private_vols);
414 for (const std::string& id : private_vols) {
415 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
416 if (pvol->getState() == VolumeBase::State::kMounted) {
417 auto evol =
418 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
419 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
420 userId));
421 evol->setMountUserId(userId);
422 pvol->addVolume(evol);
423 evol->create();
424 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
425 }
426}
427
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700428int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100429 LOG(INFO) << "onUserAdded: " << userId;
430
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700431 mAddedUsers[userId] = userSerialNumber;
432 return 0;
433}
434
435int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100436 LOG(INFO) << "onUserRemoved: " << userId;
437
Zim2d45d9b2019-11-14 16:19:05 +0000438 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700439 mAddedUsers.erase(userId);
440 return 0;
441}
442
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700443int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100444 LOG(INFO) << "onUserStarted: " << userId;
445
Zim2d45d9b2019-11-14 16:19:05 +0000446 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
447 createEmulatedVolumesForUser(userId);
448 }
449
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700450 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100451
452 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700453 return 0;
454}
455
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700456int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700457 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100458
Zim2d45d9b2019-11-14 16:19:05 +0000459 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100460 destroyEmulatedVolumesForUser(userId);
461 }
462
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700463 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700464 return 0;
465}
466
Martijn Coenencf5916f2020-01-03 14:36:45 +0100467void VolumeManager::createPendingDisksIfNeeded() {
468 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
469 if (!mSecureKeyguardShowing && userZeroStarted) {
470 // Now that secure keyguard has been dismissed and user 0 has
471 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700472 for (const auto& disk : mPendingDisks) {
473 disk->create();
474 mDisks.push_back(disk);
475 }
476 mPendingDisks.clear();
477 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100478}
479
480int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
481 mSecureKeyguardShowing = isShowing;
482 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700483 return 0;
484}
485
Narayan Kamath02efdf52019-11-27 10:53:51 +0000486// This code is executed after a fork so it's very important that the set of
487// methods we call here is strictly limited.
488//
489// TODO: Get rid of this guesswork altogether and instead exec a process
490// immediately after fork to do our bindding for us.
491static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000492 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000493 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000494 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000495 strerror(errno));
496 return false;
497 }
498
499 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
500 // to also protect against future changes that may cause issues across a
501 // fork.
502 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
503 errno != ENOENT) {
504 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
505 strerror(errno));
506 return false;
507 }
508
509 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
510 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000511 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000512 return false;
513 }
514
515 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
516 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000517 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000518 strerror(errno));
519 return false;
520 }
521
522 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
523 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000524 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000525 return false;
526 }
527
528 return true;
529}
530
Ricky Wai07e64a42020-02-11 14:31:24 +0000531// Fork the process and remount storage
532bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
533 int32_t mountMode = *static_cast<int32_t*>(params);
534 std::string userSource;
535 std::string storageSource;
536 pid_t child;
537 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800538 switch (mountMode) {
539 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000540 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800541 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000542 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800543 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000544 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700545 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000546 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800547 break;
Zim981222f2019-09-09 10:24:44 +0100548 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000549 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800550 default:
551 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000552 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800553 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000554 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700555
Ricky Wai07e64a42020-02-11 14:31:24 +0000556 // Fork a child to mount user-specific symlink helper into place
557 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
558 if (!(child = fork())) {
559 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
560 _exit(0);
561 } else {
562 _exit(1);
563 }
564 }
565
566 if (child == -1) {
567 PLOG(ERROR) << "Failed to fork";
568 return false;
569 } else {
570 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
571 }
572 return true;
573}
574
575// Helper function to scan all processes in /proc and call the callback if:
576// 1). pid belongs to an app process
577// 2). If input uid is 0 or it matches the process uid
578// 3). If userId is not -1 or userId matches the process userId
579bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700580 DIR* dir;
581 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600582 std::string rootName;
583 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700584 int pidFd;
585 int nsFd;
586 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700587
Jiyong Park8d21c922019-01-04 13:35:25 +0900588 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
589
Jeff Sharkey66270a22015-06-24 11:49:24 -0700590 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000591 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
592 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700593 }
594
595 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600596 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000597 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700598 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000599 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700600 }
601
Ricky Wai07e64a42020-02-11 14:31:24 +0000602 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700603 // Poke through all running PIDs look for apps running as UID
604 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700605 pid_t pid;
606 if (de->d_type != DT_DIR) continue;
607 if (!android::base::ParseInt(de->d_name, &pid)) continue;
608
Jeff Sharkey66270a22015-06-24 11:49:24 -0700609 pidFd = -1;
610 nsFd = -1;
611
612 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
613 if (pidFd < 0) {
614 goto next;
615 }
616 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000617 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700618 goto next;
619 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000620 if (uid != 0 && sb.st_uid != uid) {
621 goto next;
622 }
623 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700624 goto next;
625 }
626
627 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600628 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000629 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
630 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700631 goto next;
632 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600633 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700634 goto next;
635 }
636
Jiyong Park8d21c922019-01-04 13:35:25 +0900637 if (apexUpdatable) {
638 std::string exeName;
639 // When ro.apex.bionic_updatable is set to true,
640 // some early native processes have mount namespaces that are different
641 // from that of the init. Therefore, above check can't filter them out.
642 // Since the propagation type of / is 'shared', unmounting /storage
643 // for the early native processes affects other processes including
644 // init. Filter out such processes by skipping if a process is a
645 // non-Java process whose UID is < AID_APP_START. (The UID condition
646 // is required to not filter out child processes spawned by apps.)
647 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900648 goto next;
649 }
650 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900651 goto next;
652 }
653 }
654
Jeff Sharkey66270a22015-06-24 11:49:24 -0700655 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700656 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
657 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700658 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000659 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
660 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700661 goto next;
662 }
663
Ricky Wai07e64a42020-02-11 14:31:24 +0000664 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
665 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700666 }
667
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700668 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700669 close(nsFd);
670 close(pidFd);
671 }
672 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000673 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
674 return true;
675}
676
Ricky Waia2ca11e2021-01-15 14:03:23 +0000677// In each app's namespace, unmount obb and data dirs
678static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
679 int uid, const char* targets[], int size) {
680 // This code is executed after a fork so it's very important that the set of
681 // methods we call here is strictly limited.
682 if (setns(nsFd, CLONE_NEWNS) != 0) {
683 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
684 return false;
685 }
686
687 // Unmount of Android/data/foo needs to be done before Android/data below.
688 bool result = true;
689 for (int i = 0; i < size; i++) {
690 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
691 errno != ENOENT) {
692 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
693 targets[i], strerror(errno));
694 result = false;
695 }
696 }
697
698 // Mount tmpfs on Android/data and Android/obb
699 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
700 errno != ENOENT) {
701 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
702 android_data_dir, strerror(errno));
703 result = false;
704 }
705 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
706 errno != ENOENT) {
707 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
708 android_obb_dir, strerror(errno));
709 result = false;
710 }
711 return result;
712}
713
Ricky Waie96b34f2020-05-07 16:01:33 +0100714// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
715// package dirs.
716static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
717 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000718 // This code is executed after a fork so it's very important that the set of
719 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000720 if (setns(nsFd, CLONE_NEWNS) != 0) {
721 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
722 return false;
723 }
724
Ricky Waie96b34f2020-05-07 16:01:33 +0100725 // Mount tmpfs on Android/data and Android/obb
726 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
727 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
728 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
729 android_data_dir, strerror(errno));
730 return false;
731 }
732 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
733 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
734 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
735 android_obb_dir, strerror(errno));
736 return false;
737 }
738
Ricky Wai6b122572020-02-28 16:30:47 +0000739 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100740 // Create package dir and bind mount it to the actual one.
741 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
742 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
743 targets[i], strerror(errno));
744 return false;
745 }
Ricky Wai6b122572020-02-28 16:30:47 +0000746 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
747 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
748 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000749 return false;
750 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000751 }
752 return true;
753}
754
Ricky Wai6b122572020-02-28 16:30:47 +0000755static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
756 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700757 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000758 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
759 userId, dirName.c_str(), packageName.c_str());
760 } else {
761 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
762 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000763 }
Ricky Wai6b122572020-02-28 16:30:47 +0000764}
765
766static std::string getStorageDirTarget(userid_t userId, std::string dirName,
767 std::string packageName) {
768 return StringPrintf("/storage/emulated/%d/%s/%s",
769 userId, dirName.c_str(), packageName.c_str());
770}
771
Ricky Waia2ca11e2021-01-15 14:03:23 +0000772// Fork the process and remount / unmount app data and obb dirs
773bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000774 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000775 userid_t userId = multiuser_get_user_id(uid);
776 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
777 android::base::unique_fd nsFd(
778 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
779 if (nsFd == -1) {
780 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
781 return false;
782 }
783 // Storing both Android/obb and Android/data paths.
784 int size = packageNames.size() * 2;
785
786 std::unique_ptr<std::string[]> sources(new std::string[size]);
787 std::unique_ptr<std::string[]> targets(new std::string[size]);
788 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
789 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
790 const char** sources_cstr = sources_uptr.get();
791 const char** targets_cstr = targets_uptr.get();
792
793 for (int i = 0; i < size; i += 2) {
794 std::string const& packageName = packageNames[i/2];
795 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
796 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
797 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
798 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
799
800 sources_cstr[i] = sources[i].c_str();
801 targets_cstr[i] = targets[i].c_str();
802 sources_cstr[i+1] = sources[i+1].c_str();
803 targets_cstr[i+1] = targets[i+1].c_str();
804 }
805
806 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000807 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000808 // This needs to be done before EnsureDirExists to ensure Android/ is created.
809 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000810 if (status != OK) {
811 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
812 return false;
813 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000814 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
815 if (status != OK) {
816 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
817 return false;
818 }
Ricky Wai6b122572020-02-28 16:30:47 +0000819 }
820
Ricky Waie96b34f2020-05-07 16:01:33 +0100821 char android_data_dir[PATH_MAX];
822 char android_obb_dir[PATH_MAX];
823 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
824 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
825
Ricky Wai6b122572020-02-28 16:30:47 +0000826 pid_t child;
827 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
828 // original vold process mount namespace.
829 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000830 if (doUnmount) {
831 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
832 targets_cstr, size)) {
833 _exit(0);
834 } else {
835 _exit(1);
836 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000837 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000838 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
839 sources_cstr, targets_cstr, size)) {
840 _exit(0);
841 } else {
842 _exit(1);
843 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000844 }
845 }
Ricky Wai6b122572020-02-28 16:30:47 +0000846
Ricky Wai07e64a42020-02-11 14:31:24 +0000847 if (child == -1) {
848 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000849 return false;
850 } else {
851 int status;
852 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
853 PLOG(ERROR) << "Failed to waitpid: " << child;
854 return false;
855 }
856 if (!WIFEXITED(status)) {
857 PLOG(ERROR) << "Process did not exit normally, status: " << status;
858 return false;
859 }
860 if (WEXITSTATUS(status)) {
861 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
862 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000863 }
864 }
Ricky Wai6b122572020-02-28 16:30:47 +0000865 return true;
866}
867
Ricky Waia2ca11e2021-01-15 14:03:23 +0000868int VolumeManager::handleAppStorageDirs(int uid, int pid,
869 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000870 // Only run the remount if fuse is mounted for that user.
871 userid_t userId = multiuser_get_user_id(uid);
872 bool fuseMounted = false;
873 for (auto& vol : mInternalEmulatedVolumes) {
874 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
875 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
876 if (emulatedVol) {
877 fuseMounted = emulatedVol->isFuseMounted();
878 }
879 break;
880 }
881 }
882 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000883 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000884 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700885 return 0;
886}
887
Martijn Coenen23c04452020-04-29 07:49:41 +0200888int VolumeManager::abortFuse() {
889 return android::vold::AbortFuseConnections();
890}
891
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700892int VolumeManager::reset() {
893 // Tear down all existing disks/volumes and start from a blank slate so
894 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100895 for (const auto& vol : mInternalEmulatedVolumes) {
896 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800897 }
Zima438b242019-09-25 14:37:38 +0100898 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100899
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900900 // Destroy and recreate all disks except that StubVolume disks are just
901 // destroyed and removed from both mDisks and mPendingDisks.
902 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
903 // their disk recreation on reset events should be handled from outside by
904 // calling createStubVolume() again.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700905 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700906 disk->destroy();
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900907 if (!disk->isStub()) {
908 disk->create();
909 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700910 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900911 const auto isStub = [](const auto& disk) { return disk->isStub(); };
912 mDisks.remove_if(isStub);
913 mPendingDisks.remove_if(isStub);
914
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600915 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700916 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800917 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700918 return 0;
919}
920
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700921// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700922int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100923 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700924 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700925 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700926 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100927 for (const auto& vol : mInternalEmulatedVolumes) {
928 vol->destroy();
929 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700930 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700931 disk->destroy();
932 }
Zima438b242019-09-25 14:37:38 +0100933
934 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700935 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700936 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700937 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200938
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700939 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700940}
941
Jeff Sharkey9c484982015-03-31 10:35:33 -0700942int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700943 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600944 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700945
Jeff Sharkey9c484982015-03-31 10:35:33 -0700946 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100947 for (const auto& vol : mInternalEmulatedVolumes) {
948 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700949 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700950 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700951 disk->unmountAll();
952 }
953
954 // Worst case we might have some stale mounts lurking around, so
955 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800956 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700957 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600958 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700959 return -errno;
960 }
961
962 // Some volumes can be stacked on each other, so force unmount in
963 // reverse order to give us the best chance of success.
964 std::list<std::string> toUnmount;
965 mntent* mentry;
966 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600967 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700968 if ((StartsWith(test, "/mnt/") &&
969#ifdef __ANDROID_DEBUGGABLE__
970 !StartsWith(test, "/mnt/scratch") &&
971#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100972 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100973 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700974 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600975 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700976 }
977 }
978 endmntent(fp);
979
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700980 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600981 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700982 android::vold::ForceUnmount(path);
983 }
984
985 return 0;
986}
987
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000988int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000989 int size = paths.size();
990 for (int i = 0; i < size; i++) {
991 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
992 true /* skipIfDirExists */);
993 if (result != OK) {
994 return result;
995 }
996 }
997 return OK;
998}
999
1000int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1001 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001002 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001003 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001004 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001005 return -EINVAL;
1006 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001007
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001008 // Find the volume it belongs to
1009 auto filter_fn = [&](const VolumeBase& vol) {
1010 if (vol.getState() != VolumeBase::State::kMounted) {
1011 // The volume must be mounted
1012 return false;
1013 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001014 if (!vol.isVisibleForWrite()) {
1015 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001016 return false;
1017 }
1018 if (vol.getInternalPath().empty()) {
1019 return false;
1020 }
1021 if (vol.getMountUserId() != USER_UNKNOWN &&
1022 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1023 // The app dir must be created on a volume with the same user-id
1024 return false;
1025 }
1026 if (!path.empty() && StartsWith(path, vol.getPath())) {
1027 return true;
1028 }
1029
1030 return false;
1031 };
1032 auto volume = findVolumeWithFilter(filter_fn);
1033 if (volume == nullptr) {
1034 LOG(ERROR) << "Failed to find mounted volume for " << path;
1035 return -EINVAL;
1036 }
Zimc59d7742020-01-06 21:48:16 +00001037 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1038 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1039 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1040 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001041 const std::string lowerPath =
1042 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001043
Martijn Coenen62a4b272020-01-31 15:23:09 +01001044 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1045
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001046 const int access_result = access(lowerPath.c_str(), F_OK);
1047 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001048 // Nothing to fixup
1049 return OK;
1050 }
1051
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001052 if (skipIfDirExists && access_result == 0) {
1053 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1054 // which the dir doesn't need to have correct permission for now yet.
1055 return OK;
1056 }
1057
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001058 if (volume->getType() == VolumeBase::Type::kPublic) {
1059 // On public volumes, we don't need to setup permissions, as everything goes through
1060 // FUSE; just create the dirs and be done with it.
1061 return fs_mkdirs(lowerPath.c_str(), 0700);
1062 }
1063
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001064 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001065 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1066}
1067
1068int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001069 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001070 //sdcardfs magically does this for us
1071 return OK;
1072 }
1073 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001074}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001075
Eric Biggers7e79a432022-03-01 21:19:18 +00001076int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1077 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001078 int id = mNextObbId++;
1079
Martijn Coenend6a612a2020-11-19 10:49:45 +01001080 std::string lowerSourcePath;
1081
1082 // Convert to lower filesystem path
1083 if (StartsWith(sourcePath, "/storage/")) {
1084 auto filter_fn = [&](const VolumeBase& vol) {
1085 if (vol.getState() != VolumeBase::State::kMounted) {
1086 // The volume must be mounted
1087 return false;
1088 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001089 if (!vol.isVisibleForWrite()) {
1090 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001091 return false;
1092 }
1093 if (vol.getInternalPath().empty()) {
1094 return false;
1095 }
1096 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1097 return true;
1098 }
1099
1100 return false;
1101 };
1102 auto volume = findVolumeWithFilter(filter_fn);
1103 if (volume == nullptr) {
1104 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1105 return -EINVAL;
1106 } else {
1107 lowerSourcePath =
1108 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1109 }
1110 } else {
1111 lowerSourcePath = sourcePath;
1112 }
1113
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001114 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001115 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001116 vol->create();
1117
1118 mObbVolumes.push_back(vol);
1119 *outVolId = vol->getId();
1120 return android::OK;
1121}
1122
1123int VolumeManager::destroyObb(const std::string& volId) {
1124 auto i = mObbVolumes.begin();
1125 while (i != mObbVolumes.end()) {
1126 if ((*i)->getId() == volId) {
1127 (*i)->destroy();
1128 i = mObbVolumes.erase(i);
1129 } else {
1130 ++i;
1131 }
1132 }
1133 return android::OK;
1134}
1135
Risan8c9f3322018-10-29 08:52:56 +09001136int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1137 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001138 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001139 std::string* outVolId) {
1140 dev_t stubId = --mNextStubId;
1141 auto vol = std::shared_ptr<android::vold::StubVolume>(
1142 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001143
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001144 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001145 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1146 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001147 if (flags & android::vold::Disk::Flags::kStubVisible) {
1148 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1149 } else {
1150 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1151 }
Risan82e90de2020-02-04 16:07:21 +09001152 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001153 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001154 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001155 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001156 disk->initializePartition(vol);
1157 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001158 *outVolId = vol->getId();
1159 return android::OK;
1160}
1161
1162int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001163 auto tokens = android::base::Split(volId, ":");
1164 CHECK(tokens.size() == 2);
1165 dev_t stubId;
1166 CHECK(android::base::ParseUint(tokens[1], &stubId));
1167 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001168 return android::OK;
1169}
1170
Risan8f6198d2018-10-26 20:56:45 -06001171int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001172 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001173}
1174
Risan8f6198d2018-10-26 20:56:45 -06001175int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001176 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001177}
1178
1179int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001180 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001181}