blob: eac020f1e664955e3dd5698fa0062b6e9f9c86b0 [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
Ricky Wai07e64a42020-02-11 14:31:24 +0000741
Ricky Wai6b122572020-02-28 16:30:47 +0000742// Set the namespace the app process and remount its storage directories.
743static bool remountStorageDirs(int nsFd, const char* sources[], const char* targets[], int size) {
744 // This code is executed after a fork so it's very important that the set of
745 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000746 if (setns(nsFd, CLONE_NEWNS) != 0) {
747 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
748 return false;
749 }
750
Ricky Wai6b122572020-02-28 16:30:47 +0000751 for (int i = 0; i < size; i++) {
752 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
753 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
754 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000755 return false;
756 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000757 }
758 return true;
759}
760
Ricky Wai6b122572020-02-28 16:30:47 +0000761static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
762 const std::string& packageName) {
763 if (IsFilesystemSupported("sdcardfs")) {
764 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
765 userId, dirName.c_str(), packageName.c_str());
766 } else {
767 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
768 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000769 }
Ricky Wai6b122572020-02-28 16:30:47 +0000770}
771
772static std::string getStorageDirTarget(userid_t userId, std::string dirName,
773 std::string packageName) {
774 return StringPrintf("/storage/emulated/%d/%s/%s",
775 userId, dirName.c_str(), packageName.c_str());
776}
777
778// Fork the process and remount storage
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000779bool VolumeManager::forkAndRemountStorage(int uid, int pid,
780 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000781 userid_t userId = multiuser_get_user_id(uid);
782 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
783 android::base::unique_fd nsFd(
784 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
785 if (nsFd == -1) {
786 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
787 return false;
788 }
789 // Storing both Android/obb and Android/data paths.
790 int size = packageNames.size() * 2;
791
792 std::unique_ptr<std::string[]> sources(new std::string[size]);
793 std::unique_ptr<std::string[]> targets(new std::string[size]);
794 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
795 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
796 const char** sources_cstr = sources_uptr.get();
797 const char** targets_cstr = targets_uptr.get();
798
799 for (int i = 0; i < size; i += 2) {
800 std::string const& packageName = packageNames[i/2];
801 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
802 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
803 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
804 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
805
806 sources_cstr[i] = sources[i].c_str();
807 targets_cstr[i] = targets[i].c_str();
808 sources_cstr[i+1] = sources[i+1].c_str();
809 targets_cstr[i+1] = targets[i+1].c_str();
810 }
811
812 for (int i = 0; i < size; i++) {
813 auto status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
814 if (status != OK) {
815 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
816 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000817 }
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000818 // Make sure /storage/emulated/... paths are setup correctly
819 status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000820 if (status != OK) {
821 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
822 return false;
823 }
824 }
825
826 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())) {
830 if (remountStorageDirs(nsFd, sources_cstr, targets_cstr, size)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000831 _exit(0);
832 } else {
833 _exit(1);
834 }
835 }
Ricky Wai6b122572020-02-28 16:30:47 +0000836
Ricky Wai07e64a42020-02-11 14:31:24 +0000837 if (child == -1) {
838 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000839 return false;
840 } else {
841 int status;
842 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
843 PLOG(ERROR) << "Failed to waitpid: " << child;
844 return false;
845 }
846 if (!WIFEXITED(status)) {
847 PLOG(ERROR) << "Process did not exit normally, status: " << status;
848 return false;
849 }
850 if (WEXITSTATUS(status)) {
851 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
852 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000853 }
854 }
Ricky Wai6b122572020-02-28 16:30:47 +0000855 return true;
856}
857
858int VolumeManager::remountAppStorageDirs(int uid, int pid,
859 const std::vector<std::string>& packageNames) {
860 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
861 return 0;
862 }
863 // Only run the remount if fuse is mounted for that user.
864 userid_t userId = multiuser_get_user_id(uid);
865 bool fuseMounted = false;
866 for (auto& vol : mInternalEmulatedVolumes) {
867 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
868 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
869 if (emulatedVol) {
870 fuseMounted = emulatedVol->isFuseMounted();
871 }
872 break;
873 }
874 }
875 if (fuseMounted) {
876 forkAndRemountStorage(uid, pid, packageNames);
877 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700878 return 0;
879}
880
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700881int VolumeManager::reset() {
882 // Tear down all existing disks/volumes and start from a blank slate so
883 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100884 for (const auto& vol : mInternalEmulatedVolumes) {
885 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800886 }
Zima438b242019-09-25 14:37:38 +0100887 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100888
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700889 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700890 disk->destroy();
891 disk->create();
892 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600893 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700894 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800895 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700896 return 0;
897}
898
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700899// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700900int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100901 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700902 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700903 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700904 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100905 for (const auto& vol : mInternalEmulatedVolumes) {
906 vol->destroy();
907 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700908 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700909 disk->destroy();
910 }
Zima438b242019-09-25 14:37:38 +0100911
912 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700913 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700914 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700915 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700916 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700917}
918
Jeff Sharkey9c484982015-03-31 10:35:33 -0700919int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700920 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600921 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700922
Jeff Sharkey9c484982015-03-31 10:35:33 -0700923 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100924 for (const auto& vol : mInternalEmulatedVolumes) {
925 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700926 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700927 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700928 disk->unmountAll();
929 }
930
931 // Worst case we might have some stale mounts lurking around, so
932 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800933 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700934 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600935 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700936 return -errno;
937 }
938
939 // Some volumes can be stacked on each other, so force unmount in
940 // reverse order to give us the best chance of success.
941 std::list<std::string> toUnmount;
942 mntent* mentry;
943 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600944 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700945 if ((StartsWith(test, "/mnt/") &&
946#ifdef __ANDROID_DEBUGGABLE__
947 !StartsWith(test, "/mnt/scratch") &&
948#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100949 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100950 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700951 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600952 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700953 }
954 }
955 endmntent(fp);
956
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700957 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600958 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700959 android::vold::ForceUnmount(path);
960 }
961
962 return 0;
963}
964
Martijn Coenen816f4d92020-02-18 15:06:37 +0100965int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700966 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +0100967 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600968 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700969 return -EINVAL;
970 }
Martijn Coenen13ff6682019-12-24 12:57:16 +0100971
Martijn Coenen0a7e9922020-01-24 16:17:32 +0100972 // Find the volume it belongs to
973 auto filter_fn = [&](const VolumeBase& vol) {
974 if (vol.getState() != VolumeBase::State::kMounted) {
975 // The volume must be mounted
976 return false;
977 }
978 if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
979 // and visible
980 return false;
981 }
982 if (vol.getInternalPath().empty()) {
983 return false;
984 }
985 if (vol.getMountUserId() != USER_UNKNOWN &&
986 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
987 // The app dir must be created on a volume with the same user-id
988 return false;
989 }
990 if (!path.empty() && StartsWith(path, vol.getPath())) {
991 return true;
992 }
993
994 return false;
995 };
996 auto volume = findVolumeWithFilter(filter_fn);
997 if (volume == nullptr) {
998 LOG(ERROR) << "Failed to find mounted volume for " << path;
999 return -EINVAL;
1000 }
Zimc59d7742020-01-06 21:48:16 +00001001 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1002 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1003 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1004 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001005 const std::string lowerPath =
1006 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001007
Martijn Coenen62a4b272020-01-31 15:23:09 +01001008 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1009
Martijn Coenen816f4d92020-02-18 15:06:37 +01001010 if (fixupExistingOnly && (access(lowerPath.c_str(), F_OK) != 0)) {
1011 // Nothing to fixup
1012 return OK;
1013 }
1014
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001015 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001016 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1017}
1018
1019int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
1020 if (IsFilesystemSupported("sdcardfs")) {
1021 //sdcardfs magically does this for us
1022 return OK;
1023 }
1024 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001025}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001026
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001027int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001028 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001029 int id = mNextObbId++;
1030
1031 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001032 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001033 vol->create();
1034
1035 mObbVolumes.push_back(vol);
1036 *outVolId = vol->getId();
1037 return android::OK;
1038}
1039
1040int VolumeManager::destroyObb(const std::string& volId) {
1041 auto i = mObbVolumes.begin();
1042 while (i != mObbVolumes.end()) {
1043 if ((*i)->getId() == volId) {
1044 (*i)->destroy();
1045 i = mObbVolumes.erase(i);
1046 } else {
1047 ++i;
1048 }
1049 }
1050 return android::OK;
1051}
1052
Risan8c9f3322018-10-29 08:52:56 +09001053int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1054 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001055 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001056 std::string* outVolId) {
1057 dev_t stubId = --mNextStubId;
1058 auto vol = std::shared_ptr<android::vold::StubVolume>(
1059 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001060
Risan73a7a852020-02-07 18:03:44 +09001061 int32_t passedFlags = android::vold::Disk::Flags::kStub;
1062 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1063 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Risan82e90de2020-02-04 16:07:21 +09001064 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001065 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001066 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001067 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001068 disk->initializePartition(vol);
1069 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001070 *outVolId = vol->getId();
1071 return android::OK;
1072}
1073
1074int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001075 auto tokens = android::base::Split(volId, ":");
1076 CHECK(tokens.size() == 2);
1077 dev_t stubId;
1078 CHECK(android::base::ParseUint(tokens[1], &stubId));
1079 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001080 return android::OK;
1081}
1082
Risan8f6198d2018-10-26 20:56:45 -06001083int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001084 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001085}
1086
Risan8f6198d2018-10-26 20:56:45 -06001087int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001088 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001089}
1090
1091int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001092 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001093}