blob: bc556ef0c0f5d544d3dd05ddaf0c8fac068421a5 [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();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700917 return 0;
918}
919
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700920// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700921int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100922 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700923 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700924 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700925 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100926 for (const auto& vol : mInternalEmulatedVolumes) {
927 vol->destroy();
928 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700929 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700930 disk->destroy();
931 }
Zima438b242019-09-25 14:37:38 +0100932
933 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700934 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700935 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700936 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200937
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700938 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700939}
940
Jeff Sharkey9c484982015-03-31 10:35:33 -0700941int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700942 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600943 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700944
Jeff Sharkey9c484982015-03-31 10:35:33 -0700945 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100946 for (const auto& vol : mInternalEmulatedVolumes) {
947 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700948 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700949 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700950 disk->unmountAll();
951 }
952
953 // Worst case we might have some stale mounts lurking around, so
954 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800955 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700956 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600957 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700958 return -errno;
959 }
960
961 // Some volumes can be stacked on each other, so force unmount in
962 // reverse order to give us the best chance of success.
963 std::list<std::string> toUnmount;
964 mntent* mentry;
965 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600966 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700967 if ((StartsWith(test, "/mnt/") &&
968#ifdef __ANDROID_DEBUGGABLE__
969 !StartsWith(test, "/mnt/scratch") &&
970#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100971 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100972 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700973 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600974 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700975 }
976 }
977 endmntent(fp);
978
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700979 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600980 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700981 android::vold::ForceUnmount(path);
982 }
983
984 return 0;
985}
986
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000987int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000988 int size = paths.size();
989 for (int i = 0; i < size; i++) {
990 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
991 true /* skipIfDirExists */);
992 if (result != OK) {
993 return result;
994 }
995 }
996 return OK;
997}
998
999int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1000 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001001 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001002 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001003 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001004 return -EINVAL;
1005 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001006
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001007 // Find the volume it belongs to
1008 auto filter_fn = [&](const VolumeBase& vol) {
1009 if (vol.getState() != VolumeBase::State::kMounted) {
1010 // The volume must be mounted
1011 return false;
1012 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001013 if (!vol.isVisibleForWrite()) {
1014 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001015 return false;
1016 }
1017 if (vol.getInternalPath().empty()) {
1018 return false;
1019 }
1020 if (vol.getMountUserId() != USER_UNKNOWN &&
1021 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1022 // The app dir must be created on a volume with the same user-id
1023 return false;
1024 }
1025 if (!path.empty() && StartsWith(path, vol.getPath())) {
1026 return true;
1027 }
1028
1029 return false;
1030 };
1031 auto volume = findVolumeWithFilter(filter_fn);
1032 if (volume == nullptr) {
1033 LOG(ERROR) << "Failed to find mounted volume for " << path;
1034 return -EINVAL;
1035 }
Zimc59d7742020-01-06 21:48:16 +00001036 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1037 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1038 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1039 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001040 const std::string lowerPath =
1041 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001042
Martijn Coenen62a4b272020-01-31 15:23:09 +01001043 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1044
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001045 const int access_result = access(lowerPath.c_str(), F_OK);
1046 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001047 // Nothing to fixup
1048 return OK;
1049 }
1050
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001051 if (skipIfDirExists && access_result == 0) {
1052 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1053 // which the dir doesn't need to have correct permission for now yet.
1054 return OK;
1055 }
1056
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001057 if (volume->getType() == VolumeBase::Type::kPublic) {
1058 // On public volumes, we don't need to setup permissions, as everything goes through
1059 // FUSE; just create the dirs and be done with it.
1060 return fs_mkdirs(lowerPath.c_str(), 0700);
1061 }
1062
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001063 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001064 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1065}
1066
1067int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001068 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001069 //sdcardfs magically does this for us
1070 return OK;
1071 }
1072 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001073}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001074
Eric Biggers7e79a432022-03-01 21:19:18 +00001075int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1076 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001077 int id = mNextObbId++;
1078
Martijn Coenend6a612a2020-11-19 10:49:45 +01001079 std::string lowerSourcePath;
1080
1081 // Convert to lower filesystem path
1082 if (StartsWith(sourcePath, "/storage/")) {
1083 auto filter_fn = [&](const VolumeBase& vol) {
1084 if (vol.getState() != VolumeBase::State::kMounted) {
1085 // The volume must be mounted
1086 return false;
1087 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001088 if (!vol.isVisibleForWrite()) {
1089 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001090 return false;
1091 }
1092 if (vol.getInternalPath().empty()) {
1093 return false;
1094 }
1095 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1096 return true;
1097 }
1098
1099 return false;
1100 };
1101 auto volume = findVolumeWithFilter(filter_fn);
1102 if (volume == nullptr) {
1103 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1104 return -EINVAL;
1105 } else {
1106 lowerSourcePath =
1107 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1108 }
1109 } else {
1110 lowerSourcePath = sourcePath;
1111 }
1112
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001113 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001114 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001115 vol->create();
1116
1117 mObbVolumes.push_back(vol);
1118 *outVolId = vol->getId();
1119 return android::OK;
1120}
1121
1122int VolumeManager::destroyObb(const std::string& volId) {
1123 auto i = mObbVolumes.begin();
1124 while (i != mObbVolumes.end()) {
1125 if ((*i)->getId() == volId) {
1126 (*i)->destroy();
1127 i = mObbVolumes.erase(i);
1128 } else {
1129 ++i;
1130 }
1131 }
1132 return android::OK;
1133}
1134
Risan8c9f3322018-10-29 08:52:56 +09001135int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1136 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001137 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001138 std::string* outVolId) {
1139 dev_t stubId = --mNextStubId;
1140 auto vol = std::shared_ptr<android::vold::StubVolume>(
1141 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001142
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001143 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001144 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1145 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001146 if (flags & android::vold::Disk::Flags::kStubVisible) {
1147 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1148 } else {
1149 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1150 }
Risan82e90de2020-02-04 16:07:21 +09001151 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001152 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001153 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001154 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001155 disk->initializePartition(vol);
1156 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001157 *outVolId = vol->getId();
1158 return android::OK;
1159}
1160
1161int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001162 auto tokens = android::base::Split(volId, ":");
1163 CHECK(tokens.size() == 2);
1164 dev_t stubId;
1165 CHECK(android::base::ParseUint(tokens[1], &stubId));
1166 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001167 return android::OK;
1168}
1169
Risan8f6198d2018-10-26 20:56:45 -06001170int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001171 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001172}
1173
Risan8f6198d2018-10-26 20:56:45 -06001174int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001175 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001176}
1177
1178int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001179 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001180}