blob: a7d39c114f95611624b3962a42e9517c23fb9cd7 [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Ricky Waie96b34f2020-05-07 16:01:33 +010022#include <limits.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080023#include <mntent.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/ioctl.h>
28#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080029#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070030#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070031#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070032#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080033#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070034#include <array>
San Mehata19b2502010-01-06 10:33:53 -080035
San Mehata2677e42009-12-13 10:40:18 -080036#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070037
Jiyong Park8d21c922019-01-04 13:35:25 +090038#include <ApexProperties.sysprop.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060041#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080042#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070043#include <android-base/strings.h>
Narayan Kamath02efdf52019-11-27 10:53:51 +000044#include <async_safe/log.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070045
Jeff Sharkey71ebe152013-09-17 17:24:38 -070046#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060047#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070048
Robert Craigb9e3ba52014-02-04 10:53:00 -050049#include <selinux/android.h>
50
San Mehatfd7f5872009-10-12 11:32:47 -070051#include <sysutils/NetlinkEvent.h>
52
Kenny Root344ca102012-04-03 17:23:01 -070053#include <private/android_filesystem_config.h>
54
Eric Biggersa701c452018-10-23 13:06:55 -070055#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070056
Risanac02a482018-10-31 21:59:47 -060057#include "AppFuseUtil.h"
Eric Biggersa701c452018-10-23 13:06:55 -070058#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080059#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070060#include "NetlinkManager.h"
61#include "Process.h"
62#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070063#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070064#include "VoldUtil.h"
65#include "VolumeManager.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070066#include "fs/Ext4.h"
67#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070068#include "model/EmulatedVolume.h"
69#include "model/ObbVolume.h"
Zima438b242019-09-25 14:37:38 +010070#include "model/PrivateVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090071#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080072
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000073using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070074using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070075using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070076using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070077using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060078using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080079using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000080using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080081using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080082using android::vold::DeleteDirContentsAndDir;
Ricky Wai07e64a42020-02-11 14:31:24 +000083using android::vold::EnsureDirExists;
Martijn Coenen62a4b272020-01-31 15:23:09 +010084using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070085using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070086using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010087using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010088using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010089using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080090using android::vold::Symlink;
91using android::vold::Unlink;
92using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080093using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010094using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070095
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060096static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
97
98static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
99
Sudheer Shanka53947a32018-08-01 10:24:13 -0700100static const std::string kEmptyString("");
101
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600102/* 512MiB is large enough for testing purposes */
103static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700104
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700105static const unsigned int kMajorBlockMmc = 179;
106
Ricky Wai07e64a42020-02-11 14:31:24 +0000107using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
108
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700109VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700110
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700111VolumeManager* VolumeManager::Instance() {
112 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700113 return sInstance;
114}
115
116VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800117 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600118 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900119 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700120 // For security reasons, assume that a secure keyguard is
121 // showing until we hear otherwise
122 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700123}
124
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700125VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800126
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600127int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600128 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700129 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600130 if (access(kPathVirtualDisk, F_OK) != 0) {
131 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
132 }
133
134 if (mVirtualDisk == nullptr) {
135 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
136 LOG(ERROR) << "Failed to create virtual disk";
137 return -1;
138 }
139
140 struct stat buf;
141 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
142 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
143 return -1;
144 }
145
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700146 auto disk = new android::vold::Disk(
147 "virtual", buf.st_rdev, "virtual",
148 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600149 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700150 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600151 }
152 } else {
153 if (mVirtualDisk != nullptr) {
154 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700155 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600156
157 Loop::destroyByDevice(mVirtualDiskPath.c_str());
158 mVirtualDisk = nullptr;
159 }
160
161 if (access(kPathVirtualDisk, F_OK) == 0) {
162 unlink(kPathVirtualDisk);
163 }
164 }
165 return 0;
166}
167
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700168int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800169 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700170 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800171}
172
San Mehatf1b736b2009-10-10 17:22:08 -0700173int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600174 ATRACE_NAME("VolumeManager::start");
175
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700176 // Always start from a clean slate by unmounting everything in
177 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700178 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700179
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600180 Loop::destroyAll();
181
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700182 // Assume that we always have an emulated volume on internal
183 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100184 CHECK(mInternalEmulatedVolumes.empty());
185
186 auto vol = std::shared_ptr<android::vold::VolumeBase>(
187 new android::vold::EmulatedVolume("/data/media", 0));
188 vol->setMountUserId(0);
189 vol->create();
190 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700191
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600192 // Consider creating a virtual disk
193 updateVirtualDisk();
194
San Mehatf1b736b2009-10-10 17:22:08 -0700195 return 0;
196}
197
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700198void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700199 std::lock_guard<std::mutex> lock(mLock);
200
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700201 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700202 LOG(DEBUG) << "----------------";
203 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700204 evt->dump();
205 }
San Mehatf1b736b2009-10-10 17:22:08 -0700206
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700207 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
208 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700209
210 if (devType != "disk") return;
211
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600212 int major = std::stoi(evt->findParam("MAJOR"));
213 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700214 dev_t device = makedev(major, minor);
215
216 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700217 case NetlinkEvent::Action::kAdd: {
218 for (const auto& source : mDiskSources) {
219 if (source->matches(eventPath)) {
220 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700221 // specific to virtual platforms; see Utils.cpp for details)
222 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700223 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700224 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700225 flags |= android::vold::Disk::Flags::kSd;
226 } else {
227 flags |= android::vold::Disk::Flags::kUsb;
228 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700229
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700230 auto disk =
231 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
232 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
233 break;
234 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700235 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700236 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700237 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700238 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100239 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700240 handleDiskChanged(device);
241 break;
242 }
243 case NetlinkEvent::Action::kRemove: {
244 handleDiskRemoved(device);
245 break;
246 }
247 default: {
248 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
249 break;
250 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700251 }
252}
253
Jeff Sharkey401b2602017-12-14 22:15:20 -0700254void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
255 // For security reasons, if secure keyguard is showing, wait
256 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100257 // Additionally, wait until user 0 is actually started, since we need
258 // the user to be up before we can mount a FUSE daemon to handle the disk.
259 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700260 if (mSecureKeyguardShowing) {
261 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700262 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700263 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100264 } else if (!userZeroStarted) {
265 LOG(INFO) << "Found disk at " << disk->getEventPath()
266 << " but delaying scan due to user zero not having started";
267 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700268 } else {
269 disk->create();
270 mDisks.push_back(disk);
271 }
272}
273
274void VolumeManager::handleDiskChanged(dev_t device) {
275 for (const auto& disk : mDisks) {
276 if (disk->getDevice() == device) {
277 disk->readMetadata();
278 disk->readPartitions();
279 }
280 }
281
282 // For security reasons, we ignore all pending disks, since
283 // we'll scan them once the device is unlocked
284}
285
286void VolumeManager::handleDiskRemoved(dev_t device) {
287 auto i = mDisks.begin();
288 while (i != mDisks.end()) {
289 if ((*i)->getDevice() == device) {
290 (*i)->destroy();
291 i = mDisks.erase(i);
292 } else {
293 ++i;
294 }
295 }
296 auto j = mPendingDisks.begin();
297 while (j != mPendingDisks.end()) {
298 if ((*j)->getDevice() == device) {
299 j = mPendingDisks.erase(j);
300 } else {
301 ++j;
302 }
303 }
304}
305
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700306void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800307 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700308 mDiskSources.push_back(diskSource);
309}
310
311std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
312 for (auto disk : mDisks) {
313 if (disk->getId() == id) {
314 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700315 }
316 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700317 return nullptr;
318}
San Mehatf1b736b2009-10-10 17:22:08 -0700319
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700320std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100321 for (const auto& vol : mInternalEmulatedVolumes) {
322 if (vol->getId() == id) {
323 return vol;
324 }
San Mehatf1b736b2009-10-10 17:22:08 -0700325 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700326 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700327 auto vol = disk->findVolume(id);
328 if (vol != nullptr) {
329 return vol;
330 }
331 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600332 for (const auto& vol : mObbVolumes) {
333 if (vol->getId() == id) {
334 return vol;
335 }
336 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700337 return nullptr;
338}
339
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800340void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
341 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700342 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700343 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700344 disk->listVolumes(type, list);
345 }
346}
347
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600348int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700349 std::string normalizedGuid;
350 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
351 LOG(WARNING) << "Invalid GUID " << partGuid;
352 return -1;
353 }
354
Paul Crowleyc6433a22017-10-24 14:54:43 -0700355 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700356 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
357 if (unlink(keyPath.c_str()) != 0) {
358 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700359 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700360 }
Eric Biggersa701c452018-10-23 13:06:55 -0700361 if (fscrypt_is_native()) {
362 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700363 success = false;
364 }
365 }
366 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700367}
368
Zima438b242019-09-25 14:37:38 +0100369void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
370 // Destroy and remove all unstacked EmulatedVolumes for the user
371 auto i = mInternalEmulatedVolumes.begin();
372 while (i != mInternalEmulatedVolumes.end()) {
373 auto vol = *i;
374 if (vol->getMountUserId() == userId) {
375 vol->destroy();
376 i = mInternalEmulatedVolumes.erase(i);
377 } else {
378 i++;
379 }
380 }
381
382 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
383 std::list<std::string> private_vols;
384 listVolumes(VolumeBase::Type::kPrivate, private_vols);
385 for (const std::string& id : private_vols) {
386 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
387 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
388 if (pvol->getState() == VolumeBase::State::kMounted) {
389 for (const auto& vol : pvol->getVolumes()) {
390 if (vol->getMountUserId() == userId) {
391 vols_to_remove.push_back(vol);
392 }
393 }
394 for (const auto& vol : vols_to_remove) {
395 vol->destroy();
396 pvol->removeVolume(vol);
397 }
398 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
399 }
400}
401
402void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
403 // Create unstacked EmulatedVolumes for the user
404 auto vol = std::shared_ptr<android::vold::VolumeBase>(
405 new android::vold::EmulatedVolume("/data/media", userId));
406 vol->setMountUserId(userId);
407 mInternalEmulatedVolumes.push_back(vol);
408 vol->create();
409
410 // Create stacked EmulatedVolumes for the user on each PrivateVolume
411 std::list<std::string> private_vols;
412 listVolumes(VolumeBase::Type::kPrivate, private_vols);
413 for (const std::string& id : private_vols) {
414 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
415 if (pvol->getState() == VolumeBase::State::kMounted) {
416 auto evol =
417 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
418 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
419 userId));
420 evol->setMountUserId(userId);
421 pvol->addVolume(evol);
422 evol->create();
423 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
424 }
425}
426
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700427int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100428 LOG(INFO) << "onUserAdded: " << userId;
429
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700430 mAddedUsers[userId] = userSerialNumber;
431 return 0;
432}
433
434int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100435 LOG(INFO) << "onUserRemoved: " << userId;
436
Zim2d45d9b2019-11-14 16:19:05 +0000437 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700438 mAddedUsers.erase(userId);
439 return 0;
440}
441
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700442int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100443 LOG(INFO) << "onUserStarted: " << userId;
444
Zim2d45d9b2019-11-14 16:19:05 +0000445 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
446 createEmulatedVolumesForUser(userId);
447 }
448
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700449 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100450
451 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700452 return 0;
453}
454
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700455int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700456 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100457
Zim2d45d9b2019-11-14 16:19:05 +0000458 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100459 destroyEmulatedVolumesForUser(userId);
460 }
461
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700462 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700463 return 0;
464}
465
Martijn Coenencf5916f2020-01-03 14:36:45 +0100466void VolumeManager::createPendingDisksIfNeeded() {
467 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
468 if (!mSecureKeyguardShowing && userZeroStarted) {
469 // Now that secure keyguard has been dismissed and user 0 has
470 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700471 for (const auto& disk : mPendingDisks) {
472 disk->create();
473 mDisks.push_back(disk);
474 }
475 mPendingDisks.clear();
476 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100477}
478
479int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
480 mSecureKeyguardShowing = isShowing;
481 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700482 return 0;
483}
484
Narayan Kamath02efdf52019-11-27 10:53:51 +0000485// This code is executed after a fork so it's very important that the set of
486// methods we call here is strictly limited.
487//
488// TODO: Get rid of this guesswork altogether and instead exec a process
489// immediately after fork to do our bindding for us.
490static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000491 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000492 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000493 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000494 strerror(errno));
495 return false;
496 }
497
498 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
499 // to also protect against future changes that may cause issues across a
500 // fork.
501 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
502 errno != ENOENT) {
503 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
504 strerror(errno));
505 return false;
506 }
507
508 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
509 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000510 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000511 return false;
512 }
513
514 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
515 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000516 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000517 strerror(errno));
518 return false;
519 }
520
521 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, 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 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000524 return false;
525 }
526
527 return true;
528}
529
Ricky Wai07e64a42020-02-11 14:31:24 +0000530// Fork the process and remount storage
531bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
532 int32_t mountMode = *static_cast<int32_t*>(params);
533 std::string userSource;
534 std::string storageSource;
535 pid_t child;
536 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800537 switch (mountMode) {
538 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000539 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800540 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000541 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800542 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000543 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700544 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000545 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800546 break;
Zim981222f2019-09-09 10:24:44 +0100547 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000548 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800549 default:
550 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000551 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800552 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000553 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700554
Ricky Wai07e64a42020-02-11 14:31:24 +0000555 // Fork a child to mount user-specific symlink helper into place
556 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
557 if (!(child = fork())) {
558 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
559 _exit(0);
560 } else {
561 _exit(1);
562 }
563 }
564
565 if (child == -1) {
566 PLOG(ERROR) << "Failed to fork";
567 return false;
568 } else {
569 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
570 }
571 return true;
572}
573
574// Helper function to scan all processes in /proc and call the callback if:
575// 1). pid belongs to an app process
576// 2). If input uid is 0 or it matches the process uid
577// 3). If userId is not -1 or userId matches the process userId
578bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700579 DIR* dir;
580 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600581 std::string rootName;
582 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700583 int pidFd;
584 int nsFd;
585 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700586
Jiyong Park8d21c922019-01-04 13:35:25 +0900587 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
588
Jeff Sharkey66270a22015-06-24 11:49:24 -0700589 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000590 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
591 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700592 }
593
594 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600595 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000596 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700597 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000598 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700599 }
600
Ricky Wai07e64a42020-02-11 14:31:24 +0000601 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700602 // Poke through all running PIDs look for apps running as UID
603 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700604 pid_t pid;
605 if (de->d_type != DT_DIR) continue;
606 if (!android::base::ParseInt(de->d_name, &pid)) continue;
607
Jeff Sharkey66270a22015-06-24 11:49:24 -0700608 pidFd = -1;
609 nsFd = -1;
610
611 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
612 if (pidFd < 0) {
613 goto next;
614 }
615 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000616 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700617 goto next;
618 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000619 if (uid != 0 && sb.st_uid != uid) {
620 goto next;
621 }
622 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700623 goto next;
624 }
625
626 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600627 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000628 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
629 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700630 goto next;
631 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600632 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700633 goto next;
634 }
635
Jiyong Park8d21c922019-01-04 13:35:25 +0900636 if (apexUpdatable) {
637 std::string exeName;
638 // When ro.apex.bionic_updatable is set to true,
639 // some early native processes have mount namespaces that are different
640 // from that of the init. Therefore, above check can't filter them out.
641 // Since the propagation type of / is 'shared', unmounting /storage
642 // for the early native processes affects other processes including
643 // init. Filter out such processes by skipping if a process is a
644 // non-Java process whose UID is < AID_APP_START. (The UID condition
645 // is required to not filter out child processes spawned by apps.)
646 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900647 goto next;
648 }
649 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900650 goto next;
651 }
652 }
653
Jeff Sharkey66270a22015-06-24 11:49:24 -0700654 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700655 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
656 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700657 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000658 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
659 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700660 goto next;
661 }
662
Ricky Wai07e64a42020-02-11 14:31:24 +0000663 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
664 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700665 }
666
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700667 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700668 close(nsFd);
669 close(pidFd);
670 }
671 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000672 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
673 return true;
674}
675
Ricky Waia2ca11e2021-01-15 14:03:23 +0000676// In each app's namespace, unmount obb and data dirs
677static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
678 int uid, const char* targets[], int size) {
679 // This code is executed after a fork so it's very important that the set of
680 // methods we call here is strictly limited.
681 if (setns(nsFd, CLONE_NEWNS) != 0) {
682 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
683 return false;
684 }
685
686 // Unmount of Android/data/foo needs to be done before Android/data below.
687 bool result = true;
688 for (int i = 0; i < size; i++) {
689 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
690 errno != ENOENT) {
691 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
692 targets[i], strerror(errno));
693 result = false;
694 }
695 }
696
697 // Mount tmpfs on Android/data and Android/obb
698 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
699 errno != ENOENT) {
700 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
701 android_data_dir, strerror(errno));
702 result = false;
703 }
704 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
705 errno != ENOENT) {
706 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
707 android_obb_dir, strerror(errno));
708 result = false;
709 }
710 return result;
711}
712
Ricky Waie96b34f2020-05-07 16:01:33 +0100713// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
714// package dirs.
715static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
716 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000717 // This code is executed after a fork so it's very important that the set of
718 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000719 if (setns(nsFd, CLONE_NEWNS) != 0) {
720 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
721 return false;
722 }
723
Ricky Waie96b34f2020-05-07 16:01:33 +0100724 // Mount tmpfs on Android/data and Android/obb
725 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
726 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
727 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
728 android_data_dir, strerror(errno));
729 return false;
730 }
731 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
732 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
733 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
734 android_obb_dir, strerror(errno));
735 return false;
736 }
737
Ricky Wai6b122572020-02-28 16:30:47 +0000738 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100739 // Create package dir and bind mount it to the actual one.
740 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
741 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
742 targets[i], strerror(errno));
743 return false;
744 }
Ricky Wai6b122572020-02-28 16:30:47 +0000745 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
746 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
747 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000748 return false;
749 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000750 }
751 return true;
752}
753
Ricky Wai6b122572020-02-28 16:30:47 +0000754static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
755 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700756 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000757 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
758 userId, dirName.c_str(), packageName.c_str());
759 } else {
760 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
761 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000762 }
Ricky Wai6b122572020-02-28 16:30:47 +0000763}
764
765static std::string getStorageDirTarget(userid_t userId, std::string dirName,
766 std::string packageName) {
767 return StringPrintf("/storage/emulated/%d/%s/%s",
768 userId, dirName.c_str(), packageName.c_str());
769}
770
Ricky Waia2ca11e2021-01-15 14:03:23 +0000771// Fork the process and remount / unmount app data and obb dirs
772bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000773 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000774 userid_t userId = multiuser_get_user_id(uid);
775 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
776 android::base::unique_fd nsFd(
777 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
778 if (nsFd == -1) {
779 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
780 return false;
781 }
782 // Storing both Android/obb and Android/data paths.
783 int size = packageNames.size() * 2;
784
785 std::unique_ptr<std::string[]> sources(new std::string[size]);
786 std::unique_ptr<std::string[]> targets(new std::string[size]);
787 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
788 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
789 const char** sources_cstr = sources_uptr.get();
790 const char** targets_cstr = targets_uptr.get();
791
792 for (int i = 0; i < size; i += 2) {
793 std::string const& packageName = packageNames[i/2];
794 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
795 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
796 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
797 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
798
799 sources_cstr[i] = sources[i].c_str();
800 targets_cstr[i] = targets[i].c_str();
801 sources_cstr[i+1] = sources[i+1].c_str();
802 targets_cstr[i+1] = targets[i+1].c_str();
803 }
804
805 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000806 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000807 // This needs to be done before EnsureDirExists to ensure Android/ is created.
808 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000809 if (status != OK) {
810 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
811 return false;
812 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000813 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
814 if (status != OK) {
815 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
816 return false;
817 }
Ricky Wai6b122572020-02-28 16:30:47 +0000818 }
819
Ricky Waie96b34f2020-05-07 16:01:33 +0100820 char android_data_dir[PATH_MAX];
821 char android_obb_dir[PATH_MAX];
822 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
823 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
824
Ricky Wai6b122572020-02-28 16:30:47 +0000825 pid_t child;
826 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
827 // original vold process mount namespace.
828 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000829 if (doUnmount) {
830 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
831 targets_cstr, size)) {
832 _exit(0);
833 } else {
834 _exit(1);
835 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000836 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000837 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
838 sources_cstr, targets_cstr, size)) {
839 _exit(0);
840 } else {
841 _exit(1);
842 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000843 }
844 }
Ricky Wai6b122572020-02-28 16:30:47 +0000845
Ricky Wai07e64a42020-02-11 14:31:24 +0000846 if (child == -1) {
847 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000848 return false;
849 } else {
850 int status;
851 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
852 PLOG(ERROR) << "Failed to waitpid: " << child;
853 return false;
854 }
855 if (!WIFEXITED(status)) {
856 PLOG(ERROR) << "Process did not exit normally, status: " << status;
857 return false;
858 }
859 if (WEXITSTATUS(status)) {
860 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
861 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000862 }
863 }
Ricky Wai6b122572020-02-28 16:30:47 +0000864 return true;
865}
866
Ricky Waia2ca11e2021-01-15 14:03:23 +0000867int VolumeManager::handleAppStorageDirs(int uid, int pid,
868 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000869 // Only run the remount if fuse is mounted for that user.
870 userid_t userId = multiuser_get_user_id(uid);
871 bool fuseMounted = false;
872 for (auto& vol : mInternalEmulatedVolumes) {
873 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
874 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
875 if (emulatedVol) {
876 fuseMounted = emulatedVol->isFuseMounted();
877 }
878 break;
879 }
880 }
881 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000882 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000883 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700884 return 0;
885}
886
Martijn Coenen23c04452020-04-29 07:49:41 +0200887int VolumeManager::abortFuse() {
888 return android::vold::AbortFuseConnections();
889}
890
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700891int VolumeManager::reset() {
892 // Tear down all existing disks/volumes and start from a blank slate so
893 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100894 for (const auto& vol : mInternalEmulatedVolumes) {
895 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800896 }
Zima438b242019-09-25 14:37:38 +0100897 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100898
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900899 // Destroy and recreate all disks except that StubVolume disks are just
900 // destroyed and removed from both mDisks and mPendingDisks.
901 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
902 // their disk recreation on reset events should be handled from outside by
903 // calling createStubVolume() again.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700904 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700905 disk->destroy();
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900906 if (!disk->isStub()) {
907 disk->create();
908 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700909 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900910 const auto isStub = [](const auto& disk) { return disk->isStub(); };
911 mDisks.remove_if(isStub);
912 mPendingDisks.remove_if(isStub);
913
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600914 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700915 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800916 mStartedUsers.clear();
Zim11a666b2022-05-19 16:53:22 +0100917
918 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
919 // with FUSE fds open.
920 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700921 return 0;
922}
923
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700924// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700925int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100926 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700927 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700928 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700929 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100930 for (const auto& vol : mInternalEmulatedVolumes) {
931 vol->destroy();
932 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700933 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700934 disk->destroy();
935 }
Zima438b242019-09-25 14:37:38 +0100936
937 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700938 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700939 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700940 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200941
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
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000991int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000992 int size = paths.size();
993 for (int i = 0; i < size; i++) {
994 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
995 true /* skipIfDirExists */);
996 if (result != OK) {
997 return result;
998 }
999 }
1000 return OK;
1001}
1002
1003int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1004 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001005 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001006 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001007 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001008 return -EINVAL;
1009 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001010
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001011 // Find the volume it belongs to
1012 auto filter_fn = [&](const VolumeBase& vol) {
1013 if (vol.getState() != VolumeBase::State::kMounted) {
1014 // The volume must be mounted
1015 return false;
1016 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001017 if (!vol.isVisibleForWrite()) {
1018 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001019 return false;
1020 }
1021 if (vol.getInternalPath().empty()) {
1022 return false;
1023 }
1024 if (vol.getMountUserId() != USER_UNKNOWN &&
1025 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1026 // The app dir must be created on a volume with the same user-id
1027 return false;
1028 }
1029 if (!path.empty() && StartsWith(path, vol.getPath())) {
1030 return true;
1031 }
1032
1033 return false;
1034 };
1035 auto volume = findVolumeWithFilter(filter_fn);
1036 if (volume == nullptr) {
1037 LOG(ERROR) << "Failed to find mounted volume for " << path;
1038 return -EINVAL;
1039 }
Zimc59d7742020-01-06 21:48:16 +00001040 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1041 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1042 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1043 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001044 const std::string lowerPath =
1045 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001046
Martijn Coenen62a4b272020-01-31 15:23:09 +01001047 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1048
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001049 const int access_result = access(lowerPath.c_str(), F_OK);
1050 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001051 // Nothing to fixup
1052 return OK;
1053 }
1054
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001055 if (skipIfDirExists && access_result == 0) {
1056 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1057 // which the dir doesn't need to have correct permission for now yet.
1058 return OK;
1059 }
1060
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001061 if (volume->getType() == VolumeBase::Type::kPublic) {
1062 // On public volumes, we don't need to setup permissions, as everything goes through
1063 // FUSE; just create the dirs and be done with it.
1064 return fs_mkdirs(lowerPath.c_str(), 0700);
1065 }
1066
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001067 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001068 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1069}
1070
1071int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001072 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001073 //sdcardfs magically does this for us
1074 return OK;
1075 }
1076 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001077}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001078
Eric Biggers7e79a432022-03-01 21:19:18 +00001079int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1080 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001081 int id = mNextObbId++;
1082
Martijn Coenend6a612a2020-11-19 10:49:45 +01001083 std::string lowerSourcePath;
1084
1085 // Convert to lower filesystem path
1086 if (StartsWith(sourcePath, "/storage/")) {
1087 auto filter_fn = [&](const VolumeBase& vol) {
1088 if (vol.getState() != VolumeBase::State::kMounted) {
1089 // The volume must be mounted
1090 return false;
1091 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001092 if (!vol.isVisibleForWrite()) {
1093 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001094 return false;
1095 }
1096 if (vol.getInternalPath().empty()) {
1097 return false;
1098 }
1099 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1100 return true;
1101 }
1102
1103 return false;
1104 };
1105 auto volume = findVolumeWithFilter(filter_fn);
1106 if (volume == nullptr) {
1107 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1108 return -EINVAL;
1109 } else {
1110 lowerSourcePath =
1111 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1112 }
1113 } else {
1114 lowerSourcePath = sourcePath;
1115 }
1116
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001117 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001118 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001119 vol->create();
1120
1121 mObbVolumes.push_back(vol);
1122 *outVolId = vol->getId();
1123 return android::OK;
1124}
1125
1126int VolumeManager::destroyObb(const std::string& volId) {
1127 auto i = mObbVolumes.begin();
1128 while (i != mObbVolumes.end()) {
1129 if ((*i)->getId() == volId) {
1130 (*i)->destroy();
1131 i = mObbVolumes.erase(i);
1132 } else {
1133 ++i;
1134 }
1135 }
1136 return android::OK;
1137}
1138
Risan8c9f3322018-10-29 08:52:56 +09001139int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1140 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001141 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001142 std::string* outVolId) {
1143 dev_t stubId = --mNextStubId;
1144 auto vol = std::shared_ptr<android::vold::StubVolume>(
1145 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001146
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001147 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001148 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1149 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001150 if (flags & android::vold::Disk::Flags::kStubVisible) {
1151 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1152 } else {
1153 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1154 }
Risan82e90de2020-02-04 16:07:21 +09001155 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001156 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001157 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001158 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001159 disk->initializePartition(vol);
1160 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001161 *outVolId = vol->getId();
1162 return android::OK;
1163}
1164
1165int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001166 auto tokens = android::base::Split(volId, ":");
1167 CHECK(tokens.size() == 2);
1168 dev_t stubId;
1169 CHECK(android::base::ParseUint(tokens[1], &stubId));
1170 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001171 return android::OK;
1172}
1173
Risan8f6198d2018-10-26 20:56:45 -06001174int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001175 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001176}
1177
Risan8f6198d2018-10-26 20:56:45 -06001178int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001179 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001180}
1181
1182int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001183 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001184}