blob: f64f5f62ff93a71adf442643f33cfdfd2e338d11 [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;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070086using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010087using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010088using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010089using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080090using android::vold::Symlink;
91using android::vold::Unlink;
92using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080093using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010094using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070095
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060096static const char* kPathUserMount = "/mnt/user";
97static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
98
99static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
100
Sudheer Shanka53947a32018-08-01 10:24:13 -0700101static const std::string kEmptyString("");
102
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600103/* 512MiB is large enough for testing purposes */
104static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700105
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700106static const unsigned int kMajorBlockMmc = 179;
107
Ricky Wai07e64a42020-02-11 14:31:24 +0000108using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
109
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700110VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700111
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700112VolumeManager* VolumeManager::Instance() {
113 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700114 return sInstance;
115}
116
117VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800118 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600119 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900120 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700121 // For security reasons, assume that a secure keyguard is
122 // showing until we hear otherwise
123 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700124}
125
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700126VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800127
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600128int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600129 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700130 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600131 if (access(kPathVirtualDisk, F_OK) != 0) {
132 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
133 }
134
135 if (mVirtualDisk == nullptr) {
136 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
137 LOG(ERROR) << "Failed to create virtual disk";
138 return -1;
139 }
140
141 struct stat buf;
142 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
143 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
144 return -1;
145 }
146
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700147 auto disk = new android::vold::Disk(
148 "virtual", buf.st_rdev, "virtual",
149 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600150 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700151 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600152 }
153 } else {
154 if (mVirtualDisk != nullptr) {
155 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700156 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600157
158 Loop::destroyByDevice(mVirtualDiskPath.c_str());
159 mVirtualDisk = nullptr;
160 }
161
162 if (access(kPathVirtualDisk, F_OK) == 0) {
163 unlink(kPathVirtualDisk);
164 }
165 }
166 return 0;
167}
168
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700169int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800170 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700171 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800172}
173
San Mehatf1b736b2009-10-10 17:22:08 -0700174int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600175 ATRACE_NAME("VolumeManager::start");
176
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 // Always start from a clean slate by unmounting everything in
178 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700179 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700180
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600181 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
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700233 // specific to virtual platforms; see Utils.cpp for details)
234 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700235 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700236 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700237 flags |= android::vold::Disk::Flags::kSd;
238 } else {
239 flags |= android::vold::Disk::Flags::kUsb;
240 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700241
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700242 auto disk =
243 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
244 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
245 break;
246 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700247 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700248 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700249 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700250 case NetlinkEvent::Action::kChange: {
251 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
252 handleDiskChanged(device);
253 break;
254 }
255 case NetlinkEvent::Action::kRemove: {
256 handleDiskRemoved(device);
257 break;
258 }
259 default: {
260 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
261 break;
262 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700263 }
264}
265
Jeff Sharkey401b2602017-12-14 22:15:20 -0700266void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
267 // For security reasons, if secure keyguard is showing, wait
268 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100269 // Additionally, wait until user 0 is actually started, since we need
270 // the user to be up before we can mount a FUSE daemon to handle the disk.
271 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700272 if (mSecureKeyguardShowing) {
273 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700274 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700275 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100276 } else if (!userZeroStarted) {
277 LOG(INFO) << "Found disk at " << disk->getEventPath()
278 << " but delaying scan due to user zero not having started";
279 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700280 } else {
281 disk->create();
282 mDisks.push_back(disk);
283 }
284}
285
286void VolumeManager::handleDiskChanged(dev_t device) {
287 for (const auto& disk : mDisks) {
288 if (disk->getDevice() == device) {
289 disk->readMetadata();
290 disk->readPartitions();
291 }
292 }
293
294 // For security reasons, we ignore all pending disks, since
295 // we'll scan them once the device is unlocked
296}
297
298void VolumeManager::handleDiskRemoved(dev_t device) {
299 auto i = mDisks.begin();
300 while (i != mDisks.end()) {
301 if ((*i)->getDevice() == device) {
302 (*i)->destroy();
303 i = mDisks.erase(i);
304 } else {
305 ++i;
306 }
307 }
308 auto j = mPendingDisks.begin();
309 while (j != mPendingDisks.end()) {
310 if ((*j)->getDevice() == device) {
311 j = mPendingDisks.erase(j);
312 } else {
313 ++j;
314 }
315 }
316}
317
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800319 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700320 mDiskSources.push_back(diskSource);
321}
322
323std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
324 for (auto disk : mDisks) {
325 if (disk->getId() == id) {
326 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700327 }
328 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700329 return nullptr;
330}
San Mehatf1b736b2009-10-10 17:22:08 -0700331
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700332std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100333 for (const auto& vol : mInternalEmulatedVolumes) {
334 if (vol->getId() == id) {
335 return vol;
336 }
San Mehatf1b736b2009-10-10 17:22:08 -0700337 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700338 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700339 auto vol = disk->findVolume(id);
340 if (vol != nullptr) {
341 return vol;
342 }
343 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600344 for (const auto& vol : mObbVolumes) {
345 if (vol->getId() == id) {
346 return vol;
347 }
348 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700349 return nullptr;
350}
351
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800352void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
353 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700354 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700355 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700356 disk->listVolumes(type, list);
357 }
358}
359
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600360int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700361 std::string normalizedGuid;
362 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
363 LOG(WARNING) << "Invalid GUID " << partGuid;
364 return -1;
365 }
366
Paul Crowleyc6433a22017-10-24 14:54:43 -0700367 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700368 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
369 if (unlink(keyPath.c_str()) != 0) {
370 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700371 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700372 }
Eric Biggersa701c452018-10-23 13:06:55 -0700373 if (fscrypt_is_native()) {
374 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700375 success = false;
376 }
377 }
378 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700379}
380
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700381int VolumeManager::linkPrimary(userid_t userId) {
Abhijeet Kaur01fa0e02019-12-13 10:26:32 +0000382 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
Zima438b242019-09-25 14:37:38 +0100383 std::string source(mPrimary->getPath());
384 if (mPrimary->isEmulated()) {
385 source = StringPrintf("%s/%d", source.c_str(), userId);
386 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
387 }
Zim3623a212019-07-19 16:46:53 +0100388
Zima438b242019-09-25 14:37:38 +0100389 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
390 LOG(DEBUG) << "Linking " << source << " to " << target;
391 Symlink(source, target);
Zim3623a212019-07-19 16:46:53 +0100392 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700393 return 0;
394}
395
Zima438b242019-09-25 14:37:38 +0100396void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
397 // Destroy and remove all unstacked EmulatedVolumes for the user
398 auto i = mInternalEmulatedVolumes.begin();
399 while (i != mInternalEmulatedVolumes.end()) {
400 auto vol = *i;
401 if (vol->getMountUserId() == userId) {
402 vol->destroy();
403 i = mInternalEmulatedVolumes.erase(i);
404 } else {
405 i++;
406 }
407 }
408
409 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
410 std::list<std::string> private_vols;
411 listVolumes(VolumeBase::Type::kPrivate, private_vols);
412 for (const std::string& id : private_vols) {
413 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
414 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
415 if (pvol->getState() == VolumeBase::State::kMounted) {
416 for (const auto& vol : pvol->getVolumes()) {
417 if (vol->getMountUserId() == userId) {
418 vols_to_remove.push_back(vol);
419 }
420 }
421 for (const auto& vol : vols_to_remove) {
422 vol->destroy();
423 pvol->removeVolume(vol);
424 }
425 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
426 }
427}
428
429void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
430 // Create unstacked EmulatedVolumes for the user
431 auto vol = std::shared_ptr<android::vold::VolumeBase>(
432 new android::vold::EmulatedVolume("/data/media", userId));
433 vol->setMountUserId(userId);
434 mInternalEmulatedVolumes.push_back(vol);
435 vol->create();
436
437 // Create stacked EmulatedVolumes for the user on each PrivateVolume
438 std::list<std::string> private_vols;
439 listVolumes(VolumeBase::Type::kPrivate, private_vols);
440 for (const std::string& id : private_vols) {
441 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
442 if (pvol->getState() == VolumeBase::State::kMounted) {
443 auto evol =
444 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
445 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
446 userId));
447 evol->setMountUserId(userId);
448 pvol->addVolume(evol);
449 evol->create();
450 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
451 }
452}
453
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700454int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100455 LOG(INFO) << "onUserAdded: " << userId;
456
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700457 mAddedUsers[userId] = userSerialNumber;
458 return 0;
459}
460
461int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100462 LOG(INFO) << "onUserRemoved: " << userId;
463
Zim2d45d9b2019-11-14 16:19:05 +0000464 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700465 mAddedUsers.erase(userId);
466 return 0;
467}
468
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700469int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100470 LOG(INFO) << "onUserStarted: " << userId;
471
Zim2d45d9b2019-11-14 16:19:05 +0000472 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
473 createEmulatedVolumesForUser(userId);
474 }
475
Abhijeet Kaur01fa0e02019-12-13 10:26:32 +0000476 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
Zima438b242019-09-25 14:37:38 +0100477 // Note that sometimes the system will spin up processes from Zygote
478 // before actually starting the user, so we're okay if Zygote
479 // already created this directory.
480 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
481 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
482
483 if (mPrimary) {
484 linkPrimary(userId);
485 }
486 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700487
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700488 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100489
490 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700491 return 0;
492}
493
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700494int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700495 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100496
Zim2d45d9b2019-11-14 16:19:05 +0000497 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100498 destroyEmulatedVolumesForUser(userId);
499 }
500
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700501 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700502 return 0;
503}
504
Martijn Coenencf5916f2020-01-03 14:36:45 +0100505void VolumeManager::createPendingDisksIfNeeded() {
506 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
507 if (!mSecureKeyguardShowing && userZeroStarted) {
508 // Now that secure keyguard has been dismissed and user 0 has
509 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700510 for (const auto& disk : mPendingDisks) {
511 disk->create();
512 mDisks.push_back(disk);
513 }
514 mPendingDisks.clear();
515 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100516}
517
518int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
519 mSecureKeyguardShowing = isShowing;
520 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700521 return 0;
522}
523
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700524int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
525 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700526 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700527 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700528 }
529 return 0;
530}
531
Narayan Kamath02efdf52019-11-27 10:53:51 +0000532// This code is executed after a fork so it's very important that the set of
533// methods we call here is strictly limited.
534//
535// TODO: Get rid of this guesswork altogether and instead exec a process
536// immediately after fork to do our bindding for us.
537static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000538 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000539 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000540 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000541 strerror(errno));
542 return false;
543 }
544
545 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
546 // to also protect against future changes that may cause issues across a
547 // fork.
548 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
549 errno != ENOENT) {
550 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
551 strerror(errno));
552 return false;
553 }
554
555 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
556 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000557 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000558 return false;
559 }
560
561 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
562 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000563 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000564 strerror(errno));
565 return false;
566 }
567
568 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
569 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000570 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000571 return false;
572 }
573
574 return true;
575}
576
Ricky Wai07e64a42020-02-11 14:31:24 +0000577// Fork the process and remount storage
578bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
579 int32_t mountMode = *static_cast<int32_t*>(params);
580 std::string userSource;
581 std::string storageSource;
582 pid_t child;
583 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800584 switch (mountMode) {
585 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000586 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800587 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000588 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800589 break;
590 case VoldNativeService::REMOUNT_MODE_READ:
Ricky Wai07e64a42020-02-11 14:31:24 +0000591 storageSource = "/mnt/runtime/read";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800592 break;
593 case VoldNativeService::REMOUNT_MODE_WRITE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700594 case VoldNativeService::REMOUNT_MODE_LEGACY:
595 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000596 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800597 break;
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700598 case VoldNativeService::REMOUNT_MODE_FULL:
Ricky Wai07e64a42020-02-11 14:31:24 +0000599 storageSource = "/mnt/runtime/full";
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700600 break;
Zim981222f2019-09-09 10:24:44 +0100601 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000602 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800603 default:
604 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000605 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800606 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000607 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700608
Ricky Wai07e64a42020-02-11 14:31:24 +0000609 // Fork a child to mount user-specific symlink helper into place
610 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
611 if (!(child = fork())) {
612 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
613 _exit(0);
614 } else {
615 _exit(1);
616 }
617 }
618
619 if (child == -1) {
620 PLOG(ERROR) << "Failed to fork";
621 return false;
622 } else {
623 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
624 }
625 return true;
626}
627
628// Helper function to scan all processes in /proc and call the callback if:
629// 1). pid belongs to an app process
630// 2). If input uid is 0 or it matches the process uid
631// 3). If userId is not -1 or userId matches the process userId
632bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700633 DIR* dir;
634 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600635 std::string rootName;
636 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700637 int pidFd;
638 int nsFd;
639 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700640
Jiyong Park8d21c922019-01-04 13:35:25 +0900641 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
642
Jeff Sharkey66270a22015-06-24 11:49:24 -0700643 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000644 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
645 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700646 }
647
648 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600649 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000650 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700651 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000652 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700653 }
654
Ricky Wai07e64a42020-02-11 14:31:24 +0000655 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700656 // Poke through all running PIDs look for apps running as UID
657 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700658 pid_t pid;
659 if (de->d_type != DT_DIR) continue;
660 if (!android::base::ParseInt(de->d_name, &pid)) continue;
661
Jeff Sharkey66270a22015-06-24 11:49:24 -0700662 pidFd = -1;
663 nsFd = -1;
664
665 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
666 if (pidFd < 0) {
667 goto next;
668 }
669 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000670 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700671 goto next;
672 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000673 if (uid != 0 && sb.st_uid != uid) {
674 goto next;
675 }
676 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700677 goto next;
678 }
679
680 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600681 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000682 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
683 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700684 goto next;
685 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600686 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700687 goto next;
688 }
689
Jiyong Park8d21c922019-01-04 13:35:25 +0900690 if (apexUpdatable) {
691 std::string exeName;
692 // When ro.apex.bionic_updatable is set to true,
693 // some early native processes have mount namespaces that are different
694 // from that of the init. Therefore, above check can't filter them out.
695 // Since the propagation type of / is 'shared', unmounting /storage
696 // for the early native processes affects other processes including
697 // init. Filter out such processes by skipping if a process is a
698 // non-Java process whose UID is < AID_APP_START. (The UID condition
699 // is required to not filter out child processes spawned by apps.)
700 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900701 goto next;
702 }
703 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900704 goto next;
705 }
706 }
707
Jeff Sharkey66270a22015-06-24 11:49:24 -0700708 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700709 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
710 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700711 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000712 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
713 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700714 goto next;
715 }
716
Ricky Wai07e64a42020-02-11 14:31:24 +0000717 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
718 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700719 }
720
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700721 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700722 close(nsFd);
723 close(pidFd);
724 }
725 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000726 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
727 return true;
728}
729
730int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
731 if (GetBoolProperty(android::vold::kPropFuse, false)) {
732 // TODO(135341433): Implement fuse specific logic.
733 return 0;
734 }
735 return scanProcProcesses(uid, static_cast<userid_t>(-1),
736 forkAndRemountChild, &mountMode) ? 0 : -1;
737}
738
Ricky Wai07e64a42020-02-11 14:31:24 +0000739
Ricky Waie96b34f2020-05-07 16:01:33 +0100740// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
741// package dirs.
742static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
743 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000744 // 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 Waie96b34f2020-05-07 16:01:33 +0100751 // Mount tmpfs on Android/data and Android/obb
752 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
753 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
754 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
755 android_data_dir, strerror(errno));
756 return false;
757 }
758 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
759 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
760 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
761 android_obb_dir, strerror(errno));
762 return false;
763 }
764
Ricky Wai6b122572020-02-28 16:30:47 +0000765 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100766 // Create package dir and bind mount it to the actual one.
767 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
768 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
769 targets[i], strerror(errno));
770 return false;
771 }
Ricky Wai6b122572020-02-28 16:30:47 +0000772 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
773 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
774 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000775 return false;
776 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000777 }
778 return true;
779}
780
Ricky Wai6b122572020-02-28 16:30:47 +0000781static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
782 const std::string& packageName) {
783 if (IsFilesystemSupported("sdcardfs")) {
784 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
785 userId, dirName.c_str(), packageName.c_str());
786 } else {
787 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
788 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000789 }
Ricky Wai6b122572020-02-28 16:30:47 +0000790}
791
792static std::string getStorageDirTarget(userid_t userId, std::string dirName,
793 std::string packageName) {
794 return StringPrintf("/storage/emulated/%d/%s/%s",
795 userId, dirName.c_str(), packageName.c_str());
796}
797
798// Fork the process and remount storage
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000799bool VolumeManager::forkAndRemountStorage(int uid, int pid,
800 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000801 userid_t userId = multiuser_get_user_id(uid);
802 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
803 android::base::unique_fd nsFd(
804 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
805 if (nsFd == -1) {
806 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
807 return false;
808 }
809 // Storing both Android/obb and Android/data paths.
810 int size = packageNames.size() * 2;
811
812 std::unique_ptr<std::string[]> sources(new std::string[size]);
813 std::unique_ptr<std::string[]> targets(new std::string[size]);
814 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
815 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
816 const char** sources_cstr = sources_uptr.get();
817 const char** targets_cstr = targets_uptr.get();
818
819 for (int i = 0; i < size; i += 2) {
820 std::string const& packageName = packageNames[i/2];
821 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
822 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
823 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
824 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
825
826 sources_cstr[i] = sources[i].c_str();
827 targets_cstr[i] = targets[i].c_str();
828 sources_cstr[i+1] = sources[i+1].c_str();
829 targets_cstr[i+1] = targets[i+1].c_str();
830 }
831
832 for (int i = 0; i < size; i++) {
833 auto status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
834 if (status != OK) {
835 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
836 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000837 }
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000838 // Make sure /storage/emulated/... paths are setup correctly
839 status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000840 if (status != OK) {
841 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
842 return false;
843 }
844 }
845
Ricky Waie96b34f2020-05-07 16:01:33 +0100846 char android_data_dir[PATH_MAX];
847 char android_obb_dir[PATH_MAX];
848 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
849 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
850
Ricky Wai6b122572020-02-28 16:30:47 +0000851 pid_t child;
852 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
853 // original vold process mount namespace.
854 if (!(child = fork())) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100855 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
856 sources_cstr, targets_cstr, size)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000857 _exit(0);
858 } else {
859 _exit(1);
860 }
861 }
Ricky Wai6b122572020-02-28 16:30:47 +0000862
Ricky Wai07e64a42020-02-11 14:31:24 +0000863 if (child == -1) {
864 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000865 return false;
866 } else {
867 int status;
868 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
869 PLOG(ERROR) << "Failed to waitpid: " << child;
870 return false;
871 }
872 if (!WIFEXITED(status)) {
873 PLOG(ERROR) << "Process did not exit normally, status: " << status;
874 return false;
875 }
876 if (WEXITSTATUS(status)) {
877 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
878 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000879 }
880 }
Ricky Wai6b122572020-02-28 16:30:47 +0000881 return true;
882}
883
884int VolumeManager::remountAppStorageDirs(int uid, int pid,
885 const std::vector<std::string>& packageNames) {
886 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
887 return 0;
888 }
889 // Only run the remount if fuse is mounted for that user.
890 userid_t userId = multiuser_get_user_id(uid);
891 bool fuseMounted = false;
892 for (auto& vol : mInternalEmulatedVolumes) {
893 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
894 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
895 if (emulatedVol) {
896 fuseMounted = emulatedVol->isFuseMounted();
897 }
898 break;
899 }
900 }
901 if (fuseMounted) {
902 forkAndRemountStorage(uid, pid, packageNames);
903 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700904 return 0;
905}
906
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700907int VolumeManager::reset() {
908 // Tear down all existing disks/volumes and start from a blank slate so
909 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100910 for (const auto& vol : mInternalEmulatedVolumes) {
911 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800912 }
Zima438b242019-09-25 14:37:38 +0100913 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100914
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700915 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700916 disk->destroy();
917 disk->create();
918 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600919 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700920 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800921 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700922 return 0;
923}
924
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700925// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700926int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100927 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700928 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700929 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700930 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100931 for (const auto& vol : mInternalEmulatedVolumes) {
932 vol->destroy();
933 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700934 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700935 disk->destroy();
936 }
Zima438b242019-09-25 14:37:38 +0100937
938 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700939 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700940 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700941 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700942 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700943}
944
Jeff Sharkey9c484982015-03-31 10:35:33 -0700945int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700946 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600947 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700948
Jeff Sharkey9c484982015-03-31 10:35:33 -0700949 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100950 for (const auto& vol : mInternalEmulatedVolumes) {
951 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700952 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700953 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700954 disk->unmountAll();
955 }
956
957 // Worst case we might have some stale mounts lurking around, so
958 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800959 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700960 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600961 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700962 return -errno;
963 }
964
965 // Some volumes can be stacked on each other, so force unmount in
966 // reverse order to give us the best chance of success.
967 std::list<std::string> toUnmount;
968 mntent* mentry;
969 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600970 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700971 if ((StartsWith(test, "/mnt/") &&
972#ifdef __ANDROID_DEBUGGABLE__
973 !StartsWith(test, "/mnt/scratch") &&
974#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100975 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100976 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700977 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600978 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700979 }
980 }
981 endmntent(fp);
982
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700983 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600984 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700985 android::vold::ForceUnmount(path);
986 }
987
988 return 0;
989}
990
Martijn Coenen816f4d92020-02-18 15:06:37 +0100991int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700992 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +0100993 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600994 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700995 return -EINVAL;
996 }
Martijn Coenen13ff6682019-12-24 12:57:16 +0100997
Martijn Coenen0a7e9922020-01-24 16:17:32 +0100998 // Find the volume it belongs to
999 auto filter_fn = [&](const VolumeBase& vol) {
1000 if (vol.getState() != VolumeBase::State::kMounted) {
1001 // The volume must be mounted
1002 return false;
1003 }
1004 if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
1005 // and visible
1006 return false;
1007 }
1008 if (vol.getInternalPath().empty()) {
1009 return false;
1010 }
1011 if (vol.getMountUserId() != USER_UNKNOWN &&
1012 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1013 // The app dir must be created on a volume with the same user-id
1014 return false;
1015 }
1016 if (!path.empty() && StartsWith(path, vol.getPath())) {
1017 return true;
1018 }
1019
1020 return false;
1021 };
1022 auto volume = findVolumeWithFilter(filter_fn);
1023 if (volume == nullptr) {
1024 LOG(ERROR) << "Failed to find mounted volume for " << path;
1025 return -EINVAL;
1026 }
Zimc59d7742020-01-06 21:48:16 +00001027 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1028 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1029 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1030 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001031 const std::string lowerPath =
1032 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001033
Martijn Coenen62a4b272020-01-31 15:23:09 +01001034 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1035
Martijn Coenen816f4d92020-02-18 15:06:37 +01001036 if (fixupExistingOnly && (access(lowerPath.c_str(), F_OK) != 0)) {
1037 // Nothing to fixup
1038 return OK;
1039 }
1040
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001041 if (volume->getType() == VolumeBase::Type::kPublic) {
1042 // On public volumes, we don't need to setup permissions, as everything goes through
1043 // FUSE; just create the dirs and be done with it.
1044 return fs_mkdirs(lowerPath.c_str(), 0700);
1045 }
1046
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001047 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001048 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1049}
1050
1051int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
1052 if (IsFilesystemSupported("sdcardfs")) {
1053 //sdcardfs magically does this for us
1054 return OK;
1055 }
1056 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001057}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001058
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001059int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001060 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001061 int id = mNextObbId++;
1062
1063 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001064 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001065 vol->create();
1066
1067 mObbVolumes.push_back(vol);
1068 *outVolId = vol->getId();
1069 return android::OK;
1070}
1071
1072int VolumeManager::destroyObb(const std::string& volId) {
1073 auto i = mObbVolumes.begin();
1074 while (i != mObbVolumes.end()) {
1075 if ((*i)->getId() == volId) {
1076 (*i)->destroy();
1077 i = mObbVolumes.erase(i);
1078 } else {
1079 ++i;
1080 }
1081 }
1082 return android::OK;
1083}
1084
Risan8c9f3322018-10-29 08:52:56 +09001085int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1086 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001087 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001088 std::string* outVolId) {
1089 dev_t stubId = --mNextStubId;
1090 auto vol = std::shared_ptr<android::vold::StubVolume>(
1091 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001092
Risan73a7a852020-02-07 18:03:44 +09001093 int32_t passedFlags = android::vold::Disk::Flags::kStub;
1094 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1095 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Risan82e90de2020-02-04 16:07:21 +09001096 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001097 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001098 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001099 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001100 disk->initializePartition(vol);
1101 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001102 *outVolId = vol->getId();
1103 return android::OK;
1104}
1105
1106int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001107 auto tokens = android::base::Split(volId, ":");
1108 CHECK(tokens.size() == 2);
1109 dev_t stubId;
1110 CHECK(android::base::ParseUint(tokens[1], &stubId));
1111 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001112 return android::OK;
1113}
1114
Risan8f6198d2018-10-26 20:56:45 -06001115int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001116 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001117}
1118
Risan8f6198d2018-10-26 20:56:45 -06001119int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001120 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001121}
1122
1123int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001124 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001125}