blob: 8319b248491e266883a5124f3936baedcf059213 [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Ricky Waie96b34f2020-05-07 16:01:33 +010022#include <limits.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080023#include <mntent.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/ioctl.h>
28#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080029#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070030#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070031#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070032#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080033#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070034#include <array>
San Mehata19b2502010-01-06 10:33:53 -080035
San Mehata2677e42009-12-13 10:40:18 -080036#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070037
Jiyong Park8d21c922019-01-04 13:35:25 +090038#include <ApexProperties.sysprop.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060041#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080042#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070043#include <android-base/strings.h>
Narayan Kamath02efdf52019-11-27 10:53:51 +000044#include <async_safe/log.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070045
Jeff Sharkey71ebe152013-09-17 17:24:38 -070046#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060047#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070048
Robert Craigb9e3ba52014-02-04 10:53:00 -050049#include <selinux/android.h>
50
San Mehatfd7f5872009-10-12 11:32:47 -070051#include <sysutils/NetlinkEvent.h>
52
Kenny Root344ca102012-04-03 17:23:01 -070053#include <private/android_filesystem_config.h>
54
Eric Biggersa701c452018-10-23 13:06:55 -070055#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070056
Risanac02a482018-10-31 21:59:47 -060057#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070058#include "Devmapper.h"
Eric Biggersa701c452018-10-23 13:06:55 -070059#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080060#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070061#include "NetlinkManager.h"
62#include "Process.h"
63#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070064#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070065#include "VoldUtil.h"
66#include "VolumeManager.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070067#include "fs/Ext4.h"
68#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070069#include "model/EmulatedVolume.h"
70#include "model/ObbVolume.h"
Zima438b242019-09-25 14:37:38 +010071#include "model/PrivateVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090072#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080073
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000074using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070075using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070076using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070077using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070078using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060079using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080080using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000081using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080082using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080083using android::vold::DeleteDirContentsAndDir;
Ricky Wai07e64a42020-02-11 14:31:24 +000084using android::vold::EnsureDirExists;
Martijn Coenen62a4b272020-01-31 15:23:09 +010085using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070086using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070087using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010088using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010089using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010090using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080091using android::vold::Symlink;
92using android::vold::Unlink;
93using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080094using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010095using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070096
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060097static const char* kPathUserMount = "/mnt/user";
98static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
99
100static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
101
Sudheer Shanka53947a32018-08-01 10:24:13 -0700102static const std::string kEmptyString("");
103
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600104/* 512MiB is large enough for testing purposes */
105static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700106
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700107static const unsigned int kMajorBlockMmc = 179;
108
Ricky Wai07e64a42020-02-11 14:31:24 +0000109using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
110
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700111VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700112
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700113VolumeManager* VolumeManager::Instance() {
114 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700115 return sInstance;
116}
117
118VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800119 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600120 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900121 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700122 // For security reasons, assume that a secure keyguard is
123 // showing until we hear otherwise
124 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700125}
126
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700127VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800128
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600130 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700131 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600132 if (access(kPathVirtualDisk, F_OK) != 0) {
133 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
134 }
135
136 if (mVirtualDisk == nullptr) {
137 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
138 LOG(ERROR) << "Failed to create virtual disk";
139 return -1;
140 }
141
142 struct stat buf;
143 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
144 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
145 return -1;
146 }
147
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700148 auto disk = new android::vold::Disk(
149 "virtual", buf.st_rdev, "virtual",
150 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600151 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700152 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600153 }
154 } else {
155 if (mVirtualDisk != nullptr) {
156 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700157 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600158
159 Loop::destroyByDevice(mVirtualDiskPath.c_str());
160 mVirtualDisk = nullptr;
161 }
162
163 if (access(kPathVirtualDisk, F_OK) == 0) {
164 unlink(kPathVirtualDisk);
165 }
166 }
167 return 0;
168}
169
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700170int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800171 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700172 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800173}
174
San Mehatf1b736b2009-10-10 17:22:08 -0700175int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600176 ATRACE_NAME("VolumeManager::start");
177
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700178 // Always start from a clean slate by unmounting everything in
179 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700180 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700181
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600182 Devmapper::destroyAll();
183 Loop::destroyAll();
184
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700185 // Assume that we always have an emulated volume on internal
186 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100187 CHECK(mInternalEmulatedVolumes.empty());
188
189 auto vol = std::shared_ptr<android::vold::VolumeBase>(
190 new android::vold::EmulatedVolume("/data/media", 0));
191 vol->setMountUserId(0);
192 vol->create();
193 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600195 // Consider creating a virtual disk
196 updateVirtualDisk();
197
San Mehatf1b736b2009-10-10 17:22:08 -0700198 return 0;
199}
200
201int VolumeManager::stop() {
Zima438b242019-09-25 14:37:38 +0100202 CHECK(!mInternalEmulatedVolumes.empty());
203 for (const auto& vol : mInternalEmulatedVolumes) {
204 vol->destroy();
205 }
206 mInternalEmulatedVolumes.clear();
207
San Mehatf1b736b2009-10-10 17:22:08 -0700208 return 0;
209}
210
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700211void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700212 std::lock_guard<std::mutex> lock(mLock);
213
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700214 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700215 LOG(DEBUG) << "----------------";
216 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700217 evt->dump();
218 }
San Mehatf1b736b2009-10-10 17:22:08 -0700219
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700220 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
221 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700222
223 if (devType != "disk") return;
224
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600225 int major = std::stoi(evt->findParam("MAJOR"));
226 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700227 dev_t device = makedev(major, minor);
228
229 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700230 case NetlinkEvent::Action::kAdd: {
231 for (const auto& source : mDiskSources) {
232 if (source->matches(eventPath)) {
233 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700234 // specific to virtual platforms; see Utils.cpp for details)
235 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700236 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700237 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700238 flags |= android::vold::Disk::Flags::kSd;
239 } else {
240 flags |= android::vold::Disk::Flags::kUsb;
241 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700242
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700243 auto disk =
244 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
245 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
246 break;
247 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700248 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700249 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700250 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700251 case NetlinkEvent::Action::kChange: {
252 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
253 handleDiskChanged(device);
254 break;
255 }
256 case NetlinkEvent::Action::kRemove: {
257 handleDiskRemoved(device);
258 break;
259 }
260 default: {
261 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
262 break;
263 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700264 }
265}
266
Jeff Sharkey401b2602017-12-14 22:15:20 -0700267void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
268 // For security reasons, if secure keyguard is showing, wait
269 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100270 // Additionally, wait until user 0 is actually started, since we need
271 // the user to be up before we can mount a FUSE daemon to handle the disk.
272 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700273 if (mSecureKeyguardShowing) {
274 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700275 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700276 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100277 } else if (!userZeroStarted) {
278 LOG(INFO) << "Found disk at " << disk->getEventPath()
279 << " but delaying scan due to user zero not having started";
280 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700281 } else {
282 disk->create();
283 mDisks.push_back(disk);
284 }
285}
286
287void VolumeManager::handleDiskChanged(dev_t device) {
288 for (const auto& disk : mDisks) {
289 if (disk->getDevice() == device) {
290 disk->readMetadata();
291 disk->readPartitions();
292 }
293 }
294
295 // For security reasons, we ignore all pending disks, since
296 // we'll scan them once the device is unlocked
297}
298
299void VolumeManager::handleDiskRemoved(dev_t device) {
300 auto i = mDisks.begin();
301 while (i != mDisks.end()) {
302 if ((*i)->getDevice() == device) {
303 (*i)->destroy();
304 i = mDisks.erase(i);
305 } else {
306 ++i;
307 }
308 }
309 auto j = mPendingDisks.begin();
310 while (j != mPendingDisks.end()) {
311 if ((*j)->getDevice() == device) {
312 j = mPendingDisks.erase(j);
313 } else {
314 ++j;
315 }
316 }
317}
318
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700319void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800320 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321 mDiskSources.push_back(diskSource);
322}
323
324std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
325 for (auto disk : mDisks) {
326 if (disk->getId() == id) {
327 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700328 }
329 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700330 return nullptr;
331}
San Mehatf1b736b2009-10-10 17:22:08 -0700332
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700333std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100334 for (const auto& vol : mInternalEmulatedVolumes) {
335 if (vol->getId() == id) {
336 return vol;
337 }
San Mehatf1b736b2009-10-10 17:22:08 -0700338 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700339 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700340 auto vol = disk->findVolume(id);
341 if (vol != nullptr) {
342 return vol;
343 }
344 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600345 for (const auto& vol : mObbVolumes) {
346 if (vol->getId() == id) {
347 return vol;
348 }
349 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700350 return nullptr;
351}
352
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800353void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
354 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700355 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700356 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700357 disk->listVolumes(type, list);
358 }
359}
360
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600361int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700362 std::string normalizedGuid;
363 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
364 LOG(WARNING) << "Invalid GUID " << partGuid;
365 return -1;
366 }
367
Paul Crowleyc6433a22017-10-24 14:54:43 -0700368 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700369 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
370 if (unlink(keyPath.c_str()) != 0) {
371 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700372 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700373 }
Eric Biggersa701c452018-10-23 13:06:55 -0700374 if (fscrypt_is_native()) {
375 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700376 success = false;
377 }
378 }
379 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700380}
381
Zima438b242019-09-25 14:37:38 +0100382void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
383 // Destroy and remove all unstacked EmulatedVolumes for the user
384 auto i = mInternalEmulatedVolumes.begin();
385 while (i != mInternalEmulatedVolumes.end()) {
386 auto vol = *i;
387 if (vol->getMountUserId() == userId) {
388 vol->destroy();
389 i = mInternalEmulatedVolumes.erase(i);
390 } else {
391 i++;
392 }
393 }
394
395 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
396 std::list<std::string> private_vols;
397 listVolumes(VolumeBase::Type::kPrivate, private_vols);
398 for (const std::string& id : private_vols) {
399 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
400 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
401 if (pvol->getState() == VolumeBase::State::kMounted) {
402 for (const auto& vol : pvol->getVolumes()) {
403 if (vol->getMountUserId() == userId) {
404 vols_to_remove.push_back(vol);
405 }
406 }
407 for (const auto& vol : vols_to_remove) {
408 vol->destroy();
409 pvol->removeVolume(vol);
410 }
411 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
412 }
413}
414
415void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
416 // Create unstacked EmulatedVolumes for the user
417 auto vol = std::shared_ptr<android::vold::VolumeBase>(
418 new android::vold::EmulatedVolume("/data/media", userId));
419 vol->setMountUserId(userId);
420 mInternalEmulatedVolumes.push_back(vol);
421 vol->create();
422
423 // Create stacked EmulatedVolumes for the user on each PrivateVolume
424 std::list<std::string> private_vols;
425 listVolumes(VolumeBase::Type::kPrivate, private_vols);
426 for (const std::string& id : private_vols) {
427 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
428 if (pvol->getState() == VolumeBase::State::kMounted) {
429 auto evol =
430 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
431 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
432 userId));
433 evol->setMountUserId(userId);
434 pvol->addVolume(evol);
435 evol->create();
436 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
437 }
438}
439
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700440int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100441 LOG(INFO) << "onUserAdded: " << userId;
442
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700443 mAddedUsers[userId] = userSerialNumber;
444 return 0;
445}
446
447int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100448 LOG(INFO) << "onUserRemoved: " << userId;
449
Zim2d45d9b2019-11-14 16:19:05 +0000450 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700451 mAddedUsers.erase(userId);
452 return 0;
453}
454
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700455int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100456 LOG(INFO) << "onUserStarted: " << userId;
457
Zim2d45d9b2019-11-14 16:19:05 +0000458 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
459 createEmulatedVolumesForUser(userId);
460 }
461
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700462 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100463
464 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700465 return 0;
466}
467
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700468int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700469 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100470
Zim2d45d9b2019-11-14 16:19:05 +0000471 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100472 destroyEmulatedVolumesForUser(userId);
473 }
474
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700475 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700476 return 0;
477}
478
Martijn Coenencf5916f2020-01-03 14:36:45 +0100479void VolumeManager::createPendingDisksIfNeeded() {
480 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
481 if (!mSecureKeyguardShowing && userZeroStarted) {
482 // Now that secure keyguard has been dismissed and user 0 has
483 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700484 for (const auto& disk : mPendingDisks) {
485 disk->create();
486 mDisks.push_back(disk);
487 }
488 mPendingDisks.clear();
489 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100490}
491
492int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
493 mSecureKeyguardShowing = isShowing;
494 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700495 return 0;
496}
497
Narayan Kamath02efdf52019-11-27 10:53:51 +0000498// This code is executed after a fork so it's very important that the set of
499// methods we call here is strictly limited.
500//
501// TODO: Get rid of this guesswork altogether and instead exec a process
502// immediately after fork to do our bindding for us.
503static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000504 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000505 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000506 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000507 strerror(errno));
508 return false;
509 }
510
511 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
512 // to also protect against future changes that may cause issues across a
513 // fork.
514 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
515 errno != ENOENT) {
516 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
517 strerror(errno));
518 return false;
519 }
520
521 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
522 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000523 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000524 return false;
525 }
526
527 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
528 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000529 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000530 strerror(errno));
531 return false;
532 }
533
534 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
535 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000536 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000537 return false;
538 }
539
540 return true;
541}
542
Ricky Wai07e64a42020-02-11 14:31:24 +0000543// Fork the process and remount storage
544bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
545 int32_t mountMode = *static_cast<int32_t*>(params);
546 std::string userSource;
547 std::string storageSource;
548 pid_t child;
549 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800550 switch (mountMode) {
551 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000552 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800553 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000554 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800555 break;
556 case VoldNativeService::REMOUNT_MODE_READ:
Ricky Wai07e64a42020-02-11 14:31:24 +0000557 storageSource = "/mnt/runtime/read";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800558 break;
559 case VoldNativeService::REMOUNT_MODE_WRITE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700560 case VoldNativeService::REMOUNT_MODE_LEGACY:
561 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000562 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800563 break;
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700564 case VoldNativeService::REMOUNT_MODE_FULL:
Ricky Wai07e64a42020-02-11 14:31:24 +0000565 storageSource = "/mnt/runtime/full";
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700566 break;
Zim981222f2019-09-09 10:24:44 +0100567 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000568 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800569 default:
570 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000571 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800572 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000573 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700574
Ricky Wai07e64a42020-02-11 14:31:24 +0000575 // Fork a child to mount user-specific symlink helper into place
576 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
577 if (!(child = fork())) {
578 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
579 _exit(0);
580 } else {
581 _exit(1);
582 }
583 }
584
585 if (child == -1) {
586 PLOG(ERROR) << "Failed to fork";
587 return false;
588 } else {
589 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
590 }
591 return true;
592}
593
594// Helper function to scan all processes in /proc and call the callback if:
595// 1). pid belongs to an app process
596// 2). If input uid is 0 or it matches the process uid
597// 3). If userId is not -1 or userId matches the process userId
598bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700599 DIR* dir;
600 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600601 std::string rootName;
602 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700603 int pidFd;
604 int nsFd;
605 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700606
Jiyong Park8d21c922019-01-04 13:35:25 +0900607 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
608
Jeff Sharkey66270a22015-06-24 11:49:24 -0700609 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000610 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
611 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700612 }
613
614 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600615 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000616 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700617 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000618 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700619 }
620
Ricky Wai07e64a42020-02-11 14:31:24 +0000621 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700622 // Poke through all running PIDs look for apps running as UID
623 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700624 pid_t pid;
625 if (de->d_type != DT_DIR) continue;
626 if (!android::base::ParseInt(de->d_name, &pid)) continue;
627
Jeff Sharkey66270a22015-06-24 11:49:24 -0700628 pidFd = -1;
629 nsFd = -1;
630
631 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
632 if (pidFd < 0) {
633 goto next;
634 }
635 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000636 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700637 goto next;
638 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000639 if (uid != 0 && sb.st_uid != uid) {
640 goto next;
641 }
642 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700643 goto next;
644 }
645
646 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600647 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000648 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
649 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700650 goto next;
651 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600652 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700653 goto next;
654 }
655
Jiyong Park8d21c922019-01-04 13:35:25 +0900656 if (apexUpdatable) {
657 std::string exeName;
658 // When ro.apex.bionic_updatable is set to true,
659 // some early native processes have mount namespaces that are different
660 // from that of the init. Therefore, above check can't filter them out.
661 // Since the propagation type of / is 'shared', unmounting /storage
662 // for the early native processes affects other processes including
663 // init. Filter out such processes by skipping if a process is a
664 // non-Java process whose UID is < AID_APP_START. (The UID condition
665 // is required to not filter out child processes spawned by apps.)
666 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900667 goto next;
668 }
669 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900670 goto next;
671 }
672 }
673
Jeff Sharkey66270a22015-06-24 11:49:24 -0700674 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700675 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
676 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700677 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000678 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
679 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700680 goto next;
681 }
682
Ricky Wai07e64a42020-02-11 14:31:24 +0000683 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
684 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700685 }
686
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700687 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700688 close(nsFd);
689 close(pidFd);
690 }
691 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000692 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
693 return true;
694}
695
Ricky Waie96b34f2020-05-07 16:01:33 +0100696// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
697// package dirs.
698static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
699 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000700 // This code is executed after a fork so it's very important that the set of
701 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000702 if (setns(nsFd, CLONE_NEWNS) != 0) {
703 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
704 return false;
705 }
706
Ricky Waie96b34f2020-05-07 16:01:33 +0100707 // Mount tmpfs on Android/data and Android/obb
708 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
709 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
710 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
711 android_data_dir, strerror(errno));
712 return false;
713 }
714 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
715 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
716 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
717 android_obb_dir, strerror(errno));
718 return false;
719 }
720
Ricky Wai6b122572020-02-28 16:30:47 +0000721 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100722 // Create package dir and bind mount it to the actual one.
723 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
724 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
725 targets[i], strerror(errno));
726 return false;
727 }
Ricky Wai6b122572020-02-28 16:30:47 +0000728 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
729 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
730 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000731 return false;
732 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000733 }
734 return true;
735}
736
Ricky Wai6b122572020-02-28 16:30:47 +0000737static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
738 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700739 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000740 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
741 userId, dirName.c_str(), packageName.c_str());
742 } else {
743 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
744 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000745 }
Ricky Wai6b122572020-02-28 16:30:47 +0000746}
747
748static std::string getStorageDirTarget(userid_t userId, std::string dirName,
749 std::string packageName) {
750 return StringPrintf("/storage/emulated/%d/%s/%s",
751 userId, dirName.c_str(), packageName.c_str());
752}
753
754// Fork the process and remount storage
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000755bool VolumeManager::forkAndRemountStorage(int uid, int pid,
756 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000757 userid_t userId = multiuser_get_user_id(uid);
758 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
759 android::base::unique_fd nsFd(
760 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
761 if (nsFd == -1) {
762 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
763 return false;
764 }
765 // Storing both Android/obb and Android/data paths.
766 int size = packageNames.size() * 2;
767
768 std::unique_ptr<std::string[]> sources(new std::string[size]);
769 std::unique_ptr<std::string[]> targets(new std::string[size]);
770 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
771 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
772 const char** sources_cstr = sources_uptr.get();
773 const char** targets_cstr = targets_uptr.get();
774
775 for (int i = 0; i < size; i += 2) {
776 std::string const& packageName = packageNames[i/2];
777 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
778 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
779 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
780 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
781
782 sources_cstr[i] = sources[i].c_str();
783 targets_cstr[i] = targets[i].c_str();
784 sources_cstr[i+1] = sources[i+1].c_str();
785 targets_cstr[i+1] = targets[i+1].c_str();
786 }
787
788 for (int i = 0; i < size; i++) {
789 auto status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
790 if (status != OK) {
791 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
792 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000793 }
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000794 // Make sure /storage/emulated/... paths are setup correctly
795 status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000796 if (status != OK) {
797 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
798 return false;
799 }
800 }
801
Ricky Waie96b34f2020-05-07 16:01:33 +0100802 char android_data_dir[PATH_MAX];
803 char android_obb_dir[PATH_MAX];
804 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
805 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
806
Ricky Wai6b122572020-02-28 16:30:47 +0000807 pid_t child;
808 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
809 // original vold process mount namespace.
810 if (!(child = fork())) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100811 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
812 sources_cstr, targets_cstr, size)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000813 _exit(0);
814 } else {
815 _exit(1);
816 }
817 }
Ricky Wai6b122572020-02-28 16:30:47 +0000818
Ricky Wai07e64a42020-02-11 14:31:24 +0000819 if (child == -1) {
820 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000821 return false;
822 } else {
823 int status;
824 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
825 PLOG(ERROR) << "Failed to waitpid: " << child;
826 return false;
827 }
828 if (!WIFEXITED(status)) {
829 PLOG(ERROR) << "Process did not exit normally, status: " << status;
830 return false;
831 }
832 if (WEXITSTATUS(status)) {
833 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
834 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000835 }
836 }
Ricky Wai6b122572020-02-28 16:30:47 +0000837 return true;
838}
839
840int VolumeManager::remountAppStorageDirs(int uid, int pid,
841 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000842 // Only run the remount if fuse is mounted for that user.
843 userid_t userId = multiuser_get_user_id(uid);
844 bool fuseMounted = false;
845 for (auto& vol : mInternalEmulatedVolumes) {
846 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
847 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
848 if (emulatedVol) {
849 fuseMounted = emulatedVol->isFuseMounted();
850 }
851 break;
852 }
853 }
854 if (fuseMounted) {
855 forkAndRemountStorage(uid, pid, packageNames);
856 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700857 return 0;
858}
859
Martijn Coenen23c04452020-04-29 07:49:41 +0200860int VolumeManager::abortFuse() {
861 return android::vold::AbortFuseConnections();
862}
863
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700864int VolumeManager::reset() {
865 // Tear down all existing disks/volumes and start from a blank slate so
866 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100867 for (const auto& vol : mInternalEmulatedVolumes) {
868 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800869 }
Zima438b242019-09-25 14:37:38 +0100870 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100871
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700872 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700873 disk->destroy();
874 disk->create();
875 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600876 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700877 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800878 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700879 return 0;
880}
881
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700882// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700883int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100884 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700885 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700886 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700887 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100888 for (const auto& vol : mInternalEmulatedVolumes) {
889 vol->destroy();
890 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700891 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700892 disk->destroy();
893 }
Zima438b242019-09-25 14:37:38 +0100894
895 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700896 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700897 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700898 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200899
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700900 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700901}
902
Jeff Sharkey9c484982015-03-31 10:35:33 -0700903int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700904 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600905 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700906
Jeff Sharkey9c484982015-03-31 10:35:33 -0700907 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100908 for (const auto& vol : mInternalEmulatedVolumes) {
909 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700910 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700911 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700912 disk->unmountAll();
913 }
914
915 // Worst case we might have some stale mounts lurking around, so
916 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800917 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700918 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600919 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700920 return -errno;
921 }
922
923 // Some volumes can be stacked on each other, so force unmount in
924 // reverse order to give us the best chance of success.
925 std::list<std::string> toUnmount;
926 mntent* mentry;
927 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600928 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700929 if ((StartsWith(test, "/mnt/") &&
930#ifdef __ANDROID_DEBUGGABLE__
931 !StartsWith(test, "/mnt/scratch") &&
932#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100933 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100934 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700935 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600936 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700937 }
938 }
939 endmntent(fp);
940
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700941 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600942 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700943 android::vold::ForceUnmount(path);
944 }
945
946 return 0;
947}
948
Martijn Coenen816f4d92020-02-18 15:06:37 +0100949int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700950 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +0100951 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600952 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700953 return -EINVAL;
954 }
Martijn Coenen13ff6682019-12-24 12:57:16 +0100955
Martijn Coenen0a7e9922020-01-24 16:17:32 +0100956 // Find the volume it belongs to
957 auto filter_fn = [&](const VolumeBase& vol) {
958 if (vol.getState() != VolumeBase::State::kMounted) {
959 // The volume must be mounted
960 return false;
961 }
962 if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
963 // and visible
964 return false;
965 }
966 if (vol.getInternalPath().empty()) {
967 return false;
968 }
969 if (vol.getMountUserId() != USER_UNKNOWN &&
970 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
971 // The app dir must be created on a volume with the same user-id
972 return false;
973 }
974 if (!path.empty() && StartsWith(path, vol.getPath())) {
975 return true;
976 }
977
978 return false;
979 };
980 auto volume = findVolumeWithFilter(filter_fn);
981 if (volume == nullptr) {
982 LOG(ERROR) << "Failed to find mounted volume for " << path;
983 return -EINVAL;
984 }
Zimc59d7742020-01-06 21:48:16 +0000985 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
986 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
987 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
988 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +0100989 const std::string lowerPath =
990 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +0000991
Martijn Coenen62a4b272020-01-31 15:23:09 +0100992 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
993
Martijn Coenen816f4d92020-02-18 15:06:37 +0100994 if (fixupExistingOnly && (access(lowerPath.c_str(), F_OK) != 0)) {
995 // Nothing to fixup
996 return OK;
997 }
998
Martijn Coenenbf205ab2020-04-20 15:14:48 +0200999 if (volume->getType() == VolumeBase::Type::kPublic) {
1000 // On public volumes, we don't need to setup permissions, as everything goes through
1001 // FUSE; just create the dirs and be done with it.
1002 return fs_mkdirs(lowerPath.c_str(), 0700);
1003 }
1004
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001005 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001006 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1007}
1008
1009int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001010 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001011 //sdcardfs magically does this for us
1012 return OK;
1013 }
1014 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001015}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001016
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001017int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001018 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001019 int id = mNextObbId++;
1020
1021 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001022 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001023 vol->create();
1024
1025 mObbVolumes.push_back(vol);
1026 *outVolId = vol->getId();
1027 return android::OK;
1028}
1029
1030int VolumeManager::destroyObb(const std::string& volId) {
1031 auto i = mObbVolumes.begin();
1032 while (i != mObbVolumes.end()) {
1033 if ((*i)->getId() == volId) {
1034 (*i)->destroy();
1035 i = mObbVolumes.erase(i);
1036 } else {
1037 ++i;
1038 }
1039 }
1040 return android::OK;
1041}
1042
Risan8c9f3322018-10-29 08:52:56 +09001043int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1044 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001045 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001046 std::string* outVolId) {
1047 dev_t stubId = --mNextStubId;
1048 auto vol = std::shared_ptr<android::vold::StubVolume>(
1049 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001050
Risan73a7a852020-02-07 18:03:44 +09001051 int32_t passedFlags = android::vold::Disk::Flags::kStub;
1052 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1053 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Risan82e90de2020-02-04 16:07:21 +09001054 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001055 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001056 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001057 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001058 disk->initializePartition(vol);
1059 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001060 *outVolId = vol->getId();
1061 return android::OK;
1062}
1063
1064int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001065 auto tokens = android::base::Split(volId, ":");
1066 CHECK(tokens.size() == 2);
1067 dev_t stubId;
1068 CHECK(android::base::ParseUint(tokens[1], &stubId));
1069 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001070 return android::OK;
1071}
1072
Risan8f6198d2018-10-26 20:56:45 -06001073int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001074 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001075}
1076
Risan8f6198d2018-10-26 20:56:45 -06001077int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001078 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001079}
1080
1081int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001082 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001083}