blob: 9efe01a7e81bf423eb0243ea325dc280c4859cb9 [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>
Yabin Cuid1104f72015-01-02 13:28:28 -080022#include <mntent.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080028#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070029#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070030#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070033#include <array>
San Mehata19b2502010-01-06 10:33:53 -080034
San Mehata2677e42009-12-13 10:40:18 -080035#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070036
Jiyong Park8d21c922019-01-04 13:35:25 +090037#include <ApexProperties.sysprop.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080038#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070039#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060040#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080041#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070042#include <android-base/strings.h>
Narayan Kamath02efdf52019-11-27 10:53:51 +000043#include <async_safe/log.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070044
Jeff Sharkey71ebe152013-09-17 17:24:38 -070045#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060046#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070047
Robert Craigb9e3ba52014-02-04 10:53:00 -050048#include <selinux/android.h>
49
San Mehatfd7f5872009-10-12 11:32:47 -070050#include <sysutils/NetlinkEvent.h>
51
Kenny Root344ca102012-04-03 17:23:01 -070052#include <private/android_filesystem_config.h>
53
Eric Biggersa701c452018-10-23 13:06:55 -070054#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070055
Risanac02a482018-10-31 21:59:47 -060056#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070057#include "Devmapper.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;
85using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010086using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010087using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080088using android::vold::Symlink;
89using android::vold::Unlink;
90using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080091using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010092using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070093
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060094static const char* kPathUserMount = "/mnt/user";
95static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
96
97static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
98
Sudheer Shanka53947a32018-08-01 10:24:13 -070099static const std::string kEmptyString("");
100
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600101/* 512MiB is large enough for testing purposes */
102static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700103
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700104static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +0800105static const unsigned int kMajorBlockExperimentalMin = 240;
106static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700107
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 Devmapper::destroyAll();
182 Loop::destroyAll();
183
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700184 // Assume that we always have an emulated volume on internal
185 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100186 CHECK(mInternalEmulatedVolumes.empty());
187
188 auto vol = std::shared_ptr<android::vold::VolumeBase>(
189 new android::vold::EmulatedVolume("/data/media", 0));
190 vol->setMountUserId(0);
191 vol->create();
192 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700193
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600194 // Consider creating a virtual disk
195 updateVirtualDisk();
196
San Mehatf1b736b2009-10-10 17:22:08 -0700197 return 0;
198}
199
200int VolumeManager::stop() {
Zima438b242019-09-25 14:37:38 +0100201 CHECK(!mInternalEmulatedVolumes.empty());
202 for (const auto& vol : mInternalEmulatedVolumes) {
203 vol->destroy();
204 }
205 mInternalEmulatedVolumes.clear();
206
San Mehatf1b736b2009-10-10 17:22:08 -0700207 return 0;
208}
209
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700210void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700211 std::lock_guard<std::mutex> lock(mLock);
212
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700213 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700214 LOG(DEBUG) << "----------------";
215 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700216 evt->dump();
217 }
San Mehatf1b736b2009-10-10 17:22:08 -0700218
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700219 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
220 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700221
222 if (devType != "disk") return;
223
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600224 int major = std::stoi(evt->findParam("MAJOR"));
225 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700226 dev_t device = makedev(major, minor);
227
228 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700229 case NetlinkEvent::Action::kAdd: {
230 for (const auto& source : mDiskSources) {
231 if (source->matches(eventPath)) {
232 // For now, assume that MMC and virtio-blk (the latter is
233 // emulator-specific; see Disk.cpp for details) devices are SD,
234 // and that everything else is USB
235 int flags = source->getFlags();
236 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
237 major >= (int)kMajorBlockExperimentalMin &&
238 major <= (int)kMajorBlockExperimentalMax)) {
239 flags |= android::vold::Disk::Flags::kSd;
240 } else {
241 flags |= android::vold::Disk::Flags::kUsb;
242 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700243
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700244 auto disk =
245 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
246 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
247 break;
248 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700249 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700250 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700251 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700252 case NetlinkEvent::Action::kChange: {
253 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
254 handleDiskChanged(device);
255 break;
256 }
257 case NetlinkEvent::Action::kRemove: {
258 handleDiskRemoved(device);
259 break;
260 }
261 default: {
262 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
263 break;
264 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700265 }
266}
267
Jeff Sharkey401b2602017-12-14 22:15:20 -0700268void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
269 // For security reasons, if secure keyguard is showing, wait
270 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100271 // Additionally, wait until user 0 is actually started, since we need
272 // the user to be up before we can mount a FUSE daemon to handle the disk.
273 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700274 if (mSecureKeyguardShowing) {
275 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700276 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700277 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100278 } else if (!userZeroStarted) {
279 LOG(INFO) << "Found disk at " << disk->getEventPath()
280 << " but delaying scan due to user zero not having started";
281 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700282 } else {
283 disk->create();
284 mDisks.push_back(disk);
285 }
286}
287
288void VolumeManager::handleDiskChanged(dev_t device) {
289 for (const auto& disk : mDisks) {
290 if (disk->getDevice() == device) {
291 disk->readMetadata();
292 disk->readPartitions();
293 }
294 }
295
296 // For security reasons, we ignore all pending disks, since
297 // we'll scan them once the device is unlocked
298}
299
300void VolumeManager::handleDiskRemoved(dev_t device) {
301 auto i = mDisks.begin();
302 while (i != mDisks.end()) {
303 if ((*i)->getDevice() == device) {
304 (*i)->destroy();
305 i = mDisks.erase(i);
306 } else {
307 ++i;
308 }
309 }
310 auto j = mPendingDisks.begin();
311 while (j != mPendingDisks.end()) {
312 if ((*j)->getDevice() == device) {
313 j = mPendingDisks.erase(j);
314 } else {
315 ++j;
316 }
317 }
318}
319
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700320void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800321 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700322 mDiskSources.push_back(diskSource);
323}
324
325std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
326 for (auto disk : mDisks) {
327 if (disk->getId() == id) {
328 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700329 }
330 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700331 return nullptr;
332}
San Mehatf1b736b2009-10-10 17:22:08 -0700333
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700334std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100335 for (const auto& vol : mInternalEmulatedVolumes) {
336 if (vol->getId() == id) {
337 return vol;
338 }
San Mehatf1b736b2009-10-10 17:22:08 -0700339 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700340 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700341 auto vol = disk->findVolume(id);
342 if (vol != nullptr) {
343 return vol;
344 }
345 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600346 for (const auto& vol : mObbVolumes) {
347 if (vol->getId() == id) {
348 return vol;
349 }
350 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700351 return nullptr;
352}
353
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800354void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
355 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700356 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700357 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700358 disk->listVolumes(type, list);
359 }
360}
361
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600362int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700363 std::string normalizedGuid;
364 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
365 LOG(WARNING) << "Invalid GUID " << partGuid;
366 return -1;
367 }
368
Paul Crowleyc6433a22017-10-24 14:54:43 -0700369 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700370 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
371 if (unlink(keyPath.c_str()) != 0) {
372 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700373 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700374 }
Eric Biggersa701c452018-10-23 13:06:55 -0700375 if (fscrypt_is_native()) {
376 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700377 success = false;
378 }
379 }
380 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700381}
382
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700383int VolumeManager::linkPrimary(userid_t userId) {
Abhijeet Kaur01fa0e02019-12-13 10:26:32 +0000384 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
Zima438b242019-09-25 14:37:38 +0100385 std::string source(mPrimary->getPath());
386 if (mPrimary->isEmulated()) {
387 source = StringPrintf("%s/%d", source.c_str(), userId);
388 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
389 }
Zim3623a212019-07-19 16:46:53 +0100390
Zima438b242019-09-25 14:37:38 +0100391 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
392 LOG(DEBUG) << "Linking " << source << " to " << target;
393 Symlink(source, target);
Zim3623a212019-07-19 16:46:53 +0100394 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700395 return 0;
396}
397
Zima438b242019-09-25 14:37:38 +0100398void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
399 // Destroy and remove all unstacked EmulatedVolumes for the user
400 auto i = mInternalEmulatedVolumes.begin();
401 while (i != mInternalEmulatedVolumes.end()) {
402 auto vol = *i;
403 if (vol->getMountUserId() == userId) {
404 vol->destroy();
405 i = mInternalEmulatedVolumes.erase(i);
406 } else {
407 i++;
408 }
409 }
410
411 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
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 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
417 if (pvol->getState() == VolumeBase::State::kMounted) {
418 for (const auto& vol : pvol->getVolumes()) {
419 if (vol->getMountUserId() == userId) {
420 vols_to_remove.push_back(vol);
421 }
422 }
423 for (const auto& vol : vols_to_remove) {
424 vol->destroy();
425 pvol->removeVolume(vol);
426 }
427 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
428 }
429}
430
431void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
432 // Create unstacked EmulatedVolumes for the user
433 auto vol = std::shared_ptr<android::vold::VolumeBase>(
434 new android::vold::EmulatedVolume("/data/media", userId));
435 vol->setMountUserId(userId);
436 mInternalEmulatedVolumes.push_back(vol);
437 vol->create();
438
439 // Create stacked EmulatedVolumes for the user on each PrivateVolume
440 std::list<std::string> private_vols;
441 listVolumes(VolumeBase::Type::kPrivate, private_vols);
442 for (const std::string& id : private_vols) {
443 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
444 if (pvol->getState() == VolumeBase::State::kMounted) {
445 auto evol =
446 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
447 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
448 userId));
449 evol->setMountUserId(userId);
450 pvol->addVolume(evol);
451 evol->create();
452 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
453 }
454}
455
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700456int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100457 LOG(INFO) << "onUserAdded: " << userId;
458
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700459 mAddedUsers[userId] = userSerialNumber;
460 return 0;
461}
462
463int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100464 LOG(INFO) << "onUserRemoved: " << userId;
465
Zim2d45d9b2019-11-14 16:19:05 +0000466 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700467 mAddedUsers.erase(userId);
468 return 0;
469}
470
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700471int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100472 LOG(INFO) << "onUserStarted: " << userId;
473
Zim2d45d9b2019-11-14 16:19:05 +0000474 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
475 createEmulatedVolumesForUser(userId);
476 }
477
Abhijeet Kaur01fa0e02019-12-13 10:26:32 +0000478 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
Zima438b242019-09-25 14:37:38 +0100479 // Note that sometimes the system will spin up processes from Zygote
480 // before actually starting the user, so we're okay if Zygote
481 // already created this directory.
482 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
483 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
484
485 if (mPrimary) {
486 linkPrimary(userId);
487 }
488 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700489
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700490 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100491
492 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700493 return 0;
494}
495
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700496int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700497 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100498
Zim2d45d9b2019-11-14 16:19:05 +0000499 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100500 destroyEmulatedVolumesForUser(userId);
501 }
502
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700503 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700504 return 0;
505}
506
Martijn Coenencf5916f2020-01-03 14:36:45 +0100507void VolumeManager::createPendingDisksIfNeeded() {
508 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
509 if (!mSecureKeyguardShowing && userZeroStarted) {
510 // Now that secure keyguard has been dismissed and user 0 has
511 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700512 for (const auto& disk : mPendingDisks) {
513 disk->create();
514 mDisks.push_back(disk);
515 }
516 mPendingDisks.clear();
517 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100518}
519
520int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
521 mSecureKeyguardShowing = isShowing;
522 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700523 return 0;
524}
525
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700526int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
527 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700528 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700529 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700530 }
531 return 0;
532}
533
Narayan Kamath02efdf52019-11-27 10:53:51 +0000534// This code is executed after a fork so it's very important that the set of
535// methods we call here is strictly limited.
536//
537// TODO: Get rid of this guesswork altogether and instead exec a process
538// immediately after fork to do our bindding for us.
539static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000540 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000541 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000542 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000543 strerror(errno));
544 return false;
545 }
546
547 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
548 // to also protect against future changes that may cause issues across a
549 // fork.
550 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
551 errno != ENOENT) {
552 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
553 strerror(errno));
554 return false;
555 }
556
557 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
558 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000559 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000560 return false;
561 }
562
563 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
564 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000565 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000566 strerror(errno));
567 return false;
568 }
569
570 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
571 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000572 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000573 return false;
574 }
575
576 return true;
577}
578
Ricky Wai07e64a42020-02-11 14:31:24 +0000579// Fork the process and remount storage
580bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
581 int32_t mountMode = *static_cast<int32_t*>(params);
582 std::string userSource;
583 std::string storageSource;
584 pid_t child;
585 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800586 switch (mountMode) {
587 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000588 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800589 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000590 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800591 break;
592 case VoldNativeService::REMOUNT_MODE_READ:
Ricky Wai07e64a42020-02-11 14:31:24 +0000593 storageSource = "/mnt/runtime/read";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800594 break;
595 case VoldNativeService::REMOUNT_MODE_WRITE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700596 case VoldNativeService::REMOUNT_MODE_LEGACY:
597 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000598 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800599 break;
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700600 case VoldNativeService::REMOUNT_MODE_FULL:
Ricky Wai07e64a42020-02-11 14:31:24 +0000601 storageSource = "/mnt/runtime/full";
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700602 break;
Zim981222f2019-09-09 10:24:44 +0100603 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000604 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800605 default:
606 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000607 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800608 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000609 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700610
Ricky Wai07e64a42020-02-11 14:31:24 +0000611 // Fork a child to mount user-specific symlink helper into place
612 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
613 if (!(child = fork())) {
614 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
615 _exit(0);
616 } else {
617 _exit(1);
618 }
619 }
620
621 if (child == -1) {
622 PLOG(ERROR) << "Failed to fork";
623 return false;
624 } else {
625 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
626 }
627 return true;
628}
629
630// Helper function to scan all processes in /proc and call the callback if:
631// 1). pid belongs to an app process
632// 2). If input uid is 0 or it matches the process uid
633// 3). If userId is not -1 or userId matches the process userId
634bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700635 DIR* dir;
636 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600637 std::string rootName;
638 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700639 int pidFd;
640 int nsFd;
641 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700642
Jiyong Park8d21c922019-01-04 13:35:25 +0900643 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
644
Jeff Sharkey66270a22015-06-24 11:49:24 -0700645 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000646 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
647 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700648 }
649
650 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600651 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000652 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700653 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000654 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700655 }
656
Ricky Wai07e64a42020-02-11 14:31:24 +0000657 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700658 // Poke through all running PIDs look for apps running as UID
659 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700660 pid_t pid;
661 if (de->d_type != DT_DIR) continue;
662 if (!android::base::ParseInt(de->d_name, &pid)) continue;
663
Jeff Sharkey66270a22015-06-24 11:49:24 -0700664 pidFd = -1;
665 nsFd = -1;
666
667 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
668 if (pidFd < 0) {
669 goto next;
670 }
671 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000672 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700673 goto next;
674 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000675 if (uid != 0 && sb.st_uid != uid) {
676 goto next;
677 }
678 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700679 goto next;
680 }
681
682 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600683 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000684 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
685 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700686 goto next;
687 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600688 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700689 goto next;
690 }
691
Jiyong Park8d21c922019-01-04 13:35:25 +0900692 if (apexUpdatable) {
693 std::string exeName;
694 // When ro.apex.bionic_updatable is set to true,
695 // some early native processes have mount namespaces that are different
696 // from that of the init. Therefore, above check can't filter them out.
697 // Since the propagation type of / is 'shared', unmounting /storage
698 // for the early native processes affects other processes including
699 // init. Filter out such processes by skipping if a process is a
700 // non-Java process whose UID is < AID_APP_START. (The UID condition
701 // is required to not filter out child processes spawned by apps.)
702 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900703 goto next;
704 }
705 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900706 goto next;
707 }
708 }
709
Jeff Sharkey66270a22015-06-24 11:49:24 -0700710 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700711 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
712 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700713 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000714 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
715 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700716 goto next;
717 }
718
Ricky Wai07e64a42020-02-11 14:31:24 +0000719 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
720 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700721 }
722
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700723 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700724 close(nsFd);
725 close(pidFd);
726 }
727 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000728 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
729 return true;
730}
731
732int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
733 if (GetBoolProperty(android::vold::kPropFuse, false)) {
734 // TODO(135341433): Implement fuse specific logic.
735 return 0;
736 }
737 return scanProcProcesses(uid, static_cast<userid_t>(-1),
738 forkAndRemountChild, &mountMode) ? 0 : -1;
739}
740
741// Bind mount obb dir for an app if necessary.
742// How it works:
743// 1). Check if a pid is an app uid and not the FuseDaemon, if not then return.
744// 2). Get the mounts for that pid.
745// 3). If obb is already mounted then return, otherwise we need to mount obb for this pid.
746// 4). Get all packages and uid mounted for jit profile. These packages are all packages with
747// same uid or whitelisted apps.
748// 5a). If there's no package, it means it's not a process running app data isolation, so
749// just bind mount Android/obb dir.
750// 5b). Otherwise, for each package, create obb dir if it's not created and bind mount it.
751// TODO: Should we get some reliable data from system server instead of scanning /proc ?
752static bool bindMountAppObbDir(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
753 if (uid < AID_APP_START || uid > AID_APP_END) {
754 return true;
755 }
756 if (android::vold::IsFuseDaemon(pid)) {
757 return true;
758 }
759 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Start mounting obb for uid:%d, pid:%d", uid,
760 pid);
761
762 userid_t userId = multiuser_get_user_id(uid);
763 if (setns(nsFd, CLONE_NEWNS) != 0) {
764 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
765 return false;
766 }
767
768 std::string profiles_path(StringPrintf("/data/misc/profiles/cur/%d/", userId));
769 // We search both .../obb and .../obb/$PKG paths here.
770 std::string obb_path(StringPrintf("/storage/emulated/%d/Android/obb", userId));
771 int profiles_path_len = profiles_path.length();
772 int obb_path_len = obb_path.length();
773
774 // TODO: Refactor the code as a util function so we can reuse the mount parsing code.
775 std::string mounts_file(StringPrintf("/proc/%d/mounts", pid));
776 auto fp = std::unique_ptr<FILE, int (*)(FILE*)>(
777 setmntent(mounts_file.c_str(), "r"), endmntent);
778 if (!fp) {
779 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Error opening %s: %s",
780 mounts_file.c_str(), strerror(errno));
781 return false;
782 }
783
784 // Check if obb directory is mounted, and get all packages of mounted app data directory.
785 bool obb_mounted = false;
786 std::vector<std::string> pkg_name_list;
787 mntent* mentry;
788 while ((mentry = getmntent(fp.get())) != nullptr) {
789 if (strncmp(mentry->mnt_dir, profiles_path.c_str(), profiles_path_len) == 0) {
790 pkg_name_list.push_back(std::string(mentry->mnt_dir + profiles_path_len));
791 }
792 if (strncmp(mentry->mnt_dir, obb_path.c_str(), obb_path_len) == 0) {
793 obb_mounted = true;
794 }
795 }
796
797 // Obb mounted in zygote already, so skip it
798 if (obb_mounted) {
799 return true;
800 }
801
802 // Ensure obb parent directory exists
803 std::string obbSource;
804 if (IsFilesystemSupported("sdcardfs")) {
805 obbSource = StringPrintf("/mnt/runtime/default/emulated/%d/Android/obb", userId);
806 } else {
807 obbSource = StringPrintf("/mnt/pass_through/%d/emulated/%d/Android/obb", userId, userId);
808 }
809 std::string obbTarget(StringPrintf("/storage/emulated/%d/Android/obb", userId));
810 auto status = EnsureDirExists(obbSource, 0771, AID_MEDIA_RW, AID_MEDIA_RW);
811 if (status != OK) {
812 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to create dir %s %s",
813 obbSource.c_str(), strerror(-status));
814 return false;
815 }
816
817 // It means app data isolation is not applied to this, so we can just bind the whole obb
818 // directory instead.
819 if (pkg_name_list.empty()) {
820 async_safe_format_log(ANDROID_LOG_INFO, "vold",
821 "Bind mounting whole obb directory for pid %d", pid);
822 status = BindMount(obbSource, obbTarget);
823 if (status != OK) {
824 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s %s %s",
825 obbSource.c_str(), obbTarget.c_str(), strerror(-status));
826 return false;
827 }
828 return true;
829 }
830
831 // Bind mount each app's obb directory
832 for (const auto& pkg_name : pkg_name_list) {
833 std::string appObbSource;
834 if (IsFilesystemSupported("sdcardfs")) {
835 appObbSource = StringPrintf("/mnt/runtime/default/emulated/%d/Android/obb/%s",
836 userId, pkg_name.c_str());
837 } else {
838 appObbSource = StringPrintf("/mnt/pass_through/%d/emulated/%d/Android/obb/%s",
839 userId, userId, pkg_name.c_str());
840 }
841 std::string appObbTarget(StringPrintf("/storage/emulated/%d/Android/obb/%s",
842 userId, pkg_name.c_str()));
843
844 status = EnsureDirExists(appObbSource, 0770, uid, AID_MEDIA_RW);
845 if (status != OK) {
846 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Failed to ensure dir %s exists",
847 appObbSource.c_str());
848 continue;
849 }
850 async_safe_format_log(ANDROID_LOG_INFO, "vold",
851 "Bind mounting app obb directory(%s) for pid %d", pkg_name.c_str(),
852 pid);
853 status = BindMount(appObbSource, appObbTarget);
854 if (status != OK) {
855 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s %s %s",
856 obbSource.c_str(), obbTarget.c_str(), strerror(-status));
857 continue;
858 }
859 }
860 return true;
861}
862
863int VolumeManager::remountAppObb(userid_t userId) {
864 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
865 return 0;
866 }
867 LOG(INFO) << "Start remounting app obb";
868 pid_t child;
869 if (!(child = fork())) {
870 // Child process
871 if (daemon(0, 0) == -1) {
872 PLOG(FATAL) << "Cannot create daemon";
873 }
874 // TODO(149548518): Refactor the code so minimize the work after fork to prevent deadlock.
875 if (scanProcProcesses(0, userId, bindMountAppObbDir, nullptr)) {
876 // As some forked zygote processes may not setuid and recognized as an app yet, sleep
877 // 3s and try again to catch 'em all.
878 usleep(3 * 1000 * 1000); // 3s
879 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Retry remounting app obb");
880 scanProcProcesses(0, userId, bindMountAppObbDir, nullptr);
881 _exit(0);
882 } else {
883 _exit(1);
884 }
885 }
886 if (child == -1) {
887 PLOG(ERROR) << "Failed to fork";
888 return -1;
889 } else if (child == 0) {
890 // Parent
891 int stat_loc;
892 for (;;) {
893 if (waitpid(child, &stat_loc, 0) != -1 || errno != EINTR) {
894 break;
895 }
896 }
897 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700898 return 0;
899}
900
Ricky Wai07e64a42020-02-11 14:31:24 +0000901bool VolumeManager::updateFuseMountedProperty() {
902 if (mFuseMountedUsers.size() == 0) {
903 android::base::SetProperty("vold.fuse_running_users", "");
904 return true;
905 }
906 std::stringstream stream;
907 char const * sep = "";
908 for (const auto& userId : mFuseMountedUsers) {
909 stream << sep;
910 stream << userId;
911 sep = ", ";
912 }
913 return android::base::SetProperty("vold.fuse_running_users", stream.str());
914}
915
916bool VolumeManager::addFuseMountedUser(userid_t userId) {
917 mFuseMountedUsers.insert(userId);
918 return updateFuseMountedProperty();
919}
920
921bool VolumeManager::removeFuseMountedUser(userid_t userId) {
922 mFuseMountedUsers.erase(userId);
923 return updateFuseMountedProperty();
924}
925
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700926int VolumeManager::reset() {
927 // Tear down all existing disks/volumes and start from a blank slate so
928 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100929 for (const auto& vol : mInternalEmulatedVolumes) {
930 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800931 }
Zima438b242019-09-25 14:37:38 +0100932 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100933
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700934 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700935 disk->destroy();
936 disk->create();
937 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600938 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700939 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800940 mStartedUsers.clear();
Ricky Wai07e64a42020-02-11 14:31:24 +0000941 mFuseMountedUsers.clear();
942 updateFuseMountedProperty();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700943 return 0;
944}
945
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700946// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700947int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100948 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700949 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700950 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700951 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100952 for (const auto& vol : mInternalEmulatedVolumes) {
953 vol->destroy();
954 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700955 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700956 disk->destroy();
957 }
Zima438b242019-09-25 14:37:38 +0100958
959 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700960 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700961 mPendingDisks.clear();
Ricky Wai07e64a42020-02-11 14:31:24 +0000962 mFuseMountedUsers.clear();
963 updateFuseMountedProperty();
Paul Crowley56292ef2017-10-20 08:07:53 -0700964 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700965 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700966}
967
Jeff Sharkey9c484982015-03-31 10:35:33 -0700968int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700969 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600970 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700971
Jeff Sharkey9c484982015-03-31 10:35:33 -0700972 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100973 for (const auto& vol : mInternalEmulatedVolumes) {
974 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700975 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700976 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700977 disk->unmountAll();
978 }
979
980 // Worst case we might have some stale mounts lurking around, so
981 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800982 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700983 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600984 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700985 return -errno;
986 }
987
988 // Some volumes can be stacked on each other, so force unmount in
989 // reverse order to give us the best chance of success.
990 std::list<std::string> toUnmount;
991 mntent* mentry;
992 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600993 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700994 if ((StartsWith(test, "/mnt/") &&
995#ifdef __ANDROID_DEBUGGABLE__
996 !StartsWith(test, "/mnt/scratch") &&
997#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100998 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
999 !StartsWith(test, "/mnt/installer")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001000 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001001 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001002 }
1003 }
1004 endmntent(fp);
1005
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001006 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001007 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001008 android::vold::ForceUnmount(path);
1009 }
1010
1011 return 0;
1012}
1013
Martijn Coenen8a68a072020-02-12 15:29:02 +01001014int VolumeManager::setupAppDir(const std::string& path, int32_t appUid) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001015 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001016 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001017 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001018 return -EINVAL;
1019 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001020
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001021 // Find the volume it belongs to
1022 auto filter_fn = [&](const VolumeBase& vol) {
1023 if (vol.getState() != VolumeBase::State::kMounted) {
1024 // The volume must be mounted
1025 return false;
1026 }
1027 if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
1028 // and visible
1029 return false;
1030 }
1031 if (vol.getInternalPath().empty()) {
1032 return false;
1033 }
1034 if (vol.getMountUserId() != USER_UNKNOWN &&
1035 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1036 // The app dir must be created on a volume with the same user-id
1037 return false;
1038 }
1039 if (!path.empty() && StartsWith(path, vol.getPath())) {
1040 return true;
1041 }
1042
1043 return false;
1044 };
1045 auto volume = findVolumeWithFilter(filter_fn);
1046 if (volume == nullptr) {
1047 LOG(ERROR) << "Failed to find mounted volume for " << path;
1048 return -EINVAL;
1049 }
Zimc59d7742020-01-06 21:48:16 +00001050 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1051 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1052 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1053 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001054 const std::string lowerPath =
1055 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001056
Martijn Coenen62a4b272020-01-31 15:23:09 +01001057 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1058
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001059 // Create the app paths we need from the root
1060 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001061}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001062
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001063int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001064 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001065 int id = mNextObbId++;
1066
1067 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001068 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001069 vol->create();
1070
1071 mObbVolumes.push_back(vol);
1072 *outVolId = vol->getId();
1073 return android::OK;
1074}
1075
1076int VolumeManager::destroyObb(const std::string& volId) {
1077 auto i = mObbVolumes.begin();
1078 while (i != mObbVolumes.end()) {
1079 if ((*i)->getId() == volId) {
1080 (*i)->destroy();
1081 i = mObbVolumes.erase(i);
1082 } else {
1083 ++i;
1084 }
1085 }
1086 return android::OK;
1087}
1088
Risan8c9f3322018-10-29 08:52:56 +09001089int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1090 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001091 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001092 std::string* outVolId) {
1093 dev_t stubId = --mNextStubId;
1094 auto vol = std::shared_ptr<android::vold::StubVolume>(
1095 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001096
Risan73a7a852020-02-07 18:03:44 +09001097 int32_t passedFlags = android::vold::Disk::Flags::kStub;
1098 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1099 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Risan82e90de2020-02-04 16:07:21 +09001100 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001101 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001102 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001103 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001104 disk->initializePartition(vol);
1105 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001106 *outVolId = vol->getId();
1107 return android::OK;
1108}
1109
1110int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001111 auto tokens = android::base::Split(volId, ":");
1112 CHECK(tokens.size() == 2);
1113 dev_t stubId;
1114 CHECK(android::base::ParseUint(tokens[1], &stubId));
1115 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001116 return android::OK;
1117}
1118
Risan8f6198d2018-10-26 20:56:45 -06001119int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001120 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001121}
1122
Risan8f6198d2018-10-26 20:56:45 -06001123int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001124 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001125}
1126
1127int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001128 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001129}