blob: e29b920625c2c671f1b6e80d1513b97419548fe7 [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 Coenen73e30102022-07-12 08:11:02 +000084using android::vold::GetFuseMountPathForUser;
Martijn Coenen62a4b272020-01-31 15:23:09 +010085using android::vold::IsFilesystemSupported;
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -070086using android::vold::IsSdcardfsUsed;
Alistair Delvaff1fc9b2020-05-14 16:35:03 -070087using android::vold::IsVirtioBlkDevice;
Martijn Coenen62a4b272020-01-31 15:23:09 +010088using android::vold::PrepareAndroidDirs;
Martijn Coenen04bb17f2020-02-10 23:48:11 +010089using android::vold::PrepareAppDirFromRoot;
Zima438b242019-09-25 14:37:38 +010090using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080091using android::vold::Symlink;
92using android::vold::Unlink;
93using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080094using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010095using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070096
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060097static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
98
99static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
100
Sudheer Shanka53947a32018-08-01 10:24:13 -0700101static const std::string kEmptyString("");
102
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600103/* 512MiB is large enough for testing purposes */
104static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700105
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700106static const unsigned int kMajorBlockMmc = 179;
107
Ricky Wai07e64a42020-02-11 14:31:24 +0000108using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
109
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700110VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700111
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700112VolumeManager* VolumeManager::Instance() {
113 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700114 return sInstance;
115}
116
117VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800118 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600119 mNextObbId = 0;
Risan82e90de2020-02-04 16:07:21 +0900120 mNextStubId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700121 // For security reasons, assume that a secure keyguard is
122 // showing until we hear otherwise
123 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700124}
125
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700126VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800127
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600128int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600129 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700130 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600131 if (access(kPathVirtualDisk, F_OK) != 0) {
132 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
133 }
134
135 if (mVirtualDisk == nullptr) {
136 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
137 LOG(ERROR) << "Failed to create virtual disk";
138 return -1;
139 }
140
141 struct stat buf;
142 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
143 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
144 return -1;
145 }
146
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700147 auto disk = new android::vold::Disk(
148 "virtual", buf.st_rdev, "virtual",
149 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600150 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700151 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600152 }
153 } else {
154 if (mVirtualDisk != nullptr) {
155 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700156 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600157
158 Loop::destroyByDevice(mVirtualDiskPath.c_str());
159 mVirtualDisk = nullptr;
160 }
161
162 if (access(kPathVirtualDisk, F_OK) == 0) {
163 unlink(kPathVirtualDisk);
164 }
165 }
166 return 0;
167}
168
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700169int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800170 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700171 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800172}
173
San Mehatf1b736b2009-10-10 17:22:08 -0700174int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600175 ATRACE_NAME("VolumeManager::start");
176
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 // Always start from a clean slate by unmounting everything in
178 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700179 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700180
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600181 Loop::destroyAll();
182
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700183 // Assume that we always have an emulated volume on internal
184 // storage; the framework will decide if it should be mounted.
Zima438b242019-09-25 14:37:38 +0100185 CHECK(mInternalEmulatedVolumes.empty());
186
187 auto vol = std::shared_ptr<android::vold::VolumeBase>(
188 new android::vold::EmulatedVolume("/data/media", 0));
189 vol->setMountUserId(0);
190 vol->create();
191 mInternalEmulatedVolumes.push_back(vol);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600193 // Consider creating a virtual disk
194 updateVirtualDisk();
195
San Mehatf1b736b2009-10-10 17:22:08 -0700196 return 0;
197}
198
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700199void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700200 std::lock_guard<std::mutex> lock(mLock);
201
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700202 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700203 LOG(DEBUG) << "----------------";
204 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700205 evt->dump();
206 }
San Mehatf1b736b2009-10-10 17:22:08 -0700207
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700208 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
209 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700210
211 if (devType != "disk") return;
212
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600213 int major = std::stoi(evt->findParam("MAJOR"));
214 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700215 dev_t device = makedev(major, minor);
216
217 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700218 case NetlinkEvent::Action::kAdd: {
219 for (const auto& source : mDiskSources) {
220 if (source->matches(eventPath)) {
221 // For now, assume that MMC and virtio-blk (the latter is
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700222 // specific to virtual platforms; see Utils.cpp for details)
223 // devices are SD, and that everything else is USB
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700224 int flags = source->getFlags();
Alistair Delvaff1fc9b2020-05-14 16:35:03 -0700225 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700226 flags |= android::vold::Disk::Flags::kSd;
227 } else {
228 flags |= android::vold::Disk::Flags::kUsb;
229 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700230
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700231 auto disk =
232 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
233 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
234 break;
235 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700236 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700237 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700239 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100240 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700241 handleDiskChanged(device);
242 break;
243 }
244 case NetlinkEvent::Action::kRemove: {
245 handleDiskRemoved(device);
246 break;
247 }
248 default: {
249 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
250 break;
251 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700252 }
253}
254
Jeff Sharkey401b2602017-12-14 22:15:20 -0700255void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
256 // For security reasons, if secure keyguard is showing, wait
257 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100258 // Additionally, wait until user 0 is actually started, since we need
259 // the user to be up before we can mount a FUSE daemon to handle the disk.
260 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700261 if (mSecureKeyguardShowing) {
262 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700263 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700264 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100265 } else if (!userZeroStarted) {
266 LOG(INFO) << "Found disk at " << disk->getEventPath()
267 << " but delaying scan due to user zero not having started";
268 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700269 } else {
270 disk->create();
271 mDisks.push_back(disk);
272 }
273}
274
275void VolumeManager::handleDiskChanged(dev_t device) {
276 for (const auto& disk : mDisks) {
277 if (disk->getDevice() == device) {
278 disk->readMetadata();
279 disk->readPartitions();
280 }
281 }
282
283 // For security reasons, we ignore all pending disks, since
284 // we'll scan them once the device is unlocked
285}
286
287void VolumeManager::handleDiskRemoved(dev_t device) {
288 auto i = mDisks.begin();
289 while (i != mDisks.end()) {
290 if ((*i)->getDevice() == device) {
291 (*i)->destroy();
292 i = mDisks.erase(i);
293 } else {
294 ++i;
295 }
296 }
297 auto j = mPendingDisks.begin();
298 while (j != mPendingDisks.end()) {
299 if ((*j)->getDevice() == device) {
300 j = mPendingDisks.erase(j);
301 } else {
302 ++j;
303 }
304 }
305}
306
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700307void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800308 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700309 mDiskSources.push_back(diskSource);
310}
311
312std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
313 for (auto disk : mDisks) {
314 if (disk->getId() == id) {
315 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700316 }
317 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318 return nullptr;
319}
San Mehatf1b736b2009-10-10 17:22:08 -0700320
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100322 for (const auto& vol : mInternalEmulatedVolumes) {
323 if (vol->getId() == id) {
324 return vol;
325 }
San Mehatf1b736b2009-10-10 17:22:08 -0700326 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700327 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700328 auto vol = disk->findVolume(id);
329 if (vol != nullptr) {
330 return vol;
331 }
332 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600333 for (const auto& vol : mObbVolumes) {
334 if (vol->getId() == id) {
335 return vol;
336 }
337 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700338 return nullptr;
339}
340
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800341void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
342 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700343 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700344 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700345 disk->listVolumes(type, list);
346 }
347}
348
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600349int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700350 std::string normalizedGuid;
351 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
352 LOG(WARNING) << "Invalid GUID " << partGuid;
353 return -1;
354 }
355
Paul Crowleyc6433a22017-10-24 14:54:43 -0700356 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700357 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
358 if (unlink(keyPath.c_str()) != 0) {
359 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700360 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700361 }
Eric Biggersa6957c02022-06-15 18:52:18 +0000362 if (IsFbeEnabled()) {
Eric Biggersa701c452018-10-23 13:06:55 -0700363 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700364 success = false;
365 }
366 }
367 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700368}
369
Zima438b242019-09-25 14:37:38 +0100370void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
371 // Destroy and remove all unstacked EmulatedVolumes for the user
372 auto i = mInternalEmulatedVolumes.begin();
373 while (i != mInternalEmulatedVolumes.end()) {
374 auto vol = *i;
375 if (vol->getMountUserId() == userId) {
376 vol->destroy();
377 i = mInternalEmulatedVolumes.erase(i);
378 } else {
379 i++;
380 }
381 }
382
383 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
384 std::list<std::string> private_vols;
385 listVolumes(VolumeBase::Type::kPrivate, private_vols);
386 for (const std::string& id : private_vols) {
387 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
388 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
389 if (pvol->getState() == VolumeBase::State::kMounted) {
390 for (const auto& vol : pvol->getVolumes()) {
391 if (vol->getMountUserId() == userId) {
392 vols_to_remove.push_back(vol);
393 }
394 }
395 for (const auto& vol : vols_to_remove) {
396 vol->destroy();
397 pvol->removeVolume(vol);
398 }
399 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
400 }
401}
402
403void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
404 // Create unstacked EmulatedVolumes for the user
405 auto vol = std::shared_ptr<android::vold::VolumeBase>(
406 new android::vold::EmulatedVolume("/data/media", userId));
407 vol->setMountUserId(userId);
408 mInternalEmulatedVolumes.push_back(vol);
409 vol->create();
410
411 // Create stacked EmulatedVolumes for the user on each PrivateVolume
412 std::list<std::string> private_vols;
413 listVolumes(VolumeBase::Type::kPrivate, private_vols);
414 for (const std::string& id : private_vols) {
415 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
416 if (pvol->getState() == VolumeBase::State::kMounted) {
417 auto evol =
418 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
419 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
420 userId));
421 evol->setMountUserId(userId);
422 pvol->addVolume(evol);
423 evol->create();
424 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
425 }
426}
427
Martijn Coenen73e30102022-07-12 08:11:02 +0000428userid_t VolumeManager::getSharedStorageUser(userid_t userId) {
429 if (mSharedStorageUser.find(userId) == mSharedStorageUser.end()) {
430 return USER_UNKNOWN;
431 }
432 return mSharedStorageUser.at(userId);
433}
434
435int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber,
436 userid_t sharesStorageWithUserId) {
Zima438b242019-09-25 14:37:38 +0100437 LOG(INFO) << "onUserAdded: " << userId;
438
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700439 mAddedUsers[userId] = userSerialNumber;
Martijn Coenen73e30102022-07-12 08:11:02 +0000440 if (sharesStorageWithUserId != USER_UNKNOWN) {
441 mSharedStorageUser[userId] = sharesStorageWithUserId;
442 }
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700443 return 0;
444}
445
446int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100447 LOG(INFO) << "onUserRemoved: " << userId;
448
Zim2d45d9b2019-11-14 16:19:05 +0000449 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700450 mAddedUsers.erase(userId);
Martijn Coenen73e30102022-07-12 08:11:02 +0000451 mSharedStorageUser.erase(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700452 return 0;
453}
454
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700455int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100456 LOG(INFO) << "onUserStarted: " << userId;
457
Zim2d45d9b2019-11-14 16:19:05 +0000458 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
459 createEmulatedVolumesForUser(userId);
460 }
461
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700462 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100463
464 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700465 return 0;
466}
467
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700468int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700469 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100470
Zim2d45d9b2019-11-14 16:19:05 +0000471 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100472 destroyEmulatedVolumesForUser(userId);
473 }
474
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700475 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700476 return 0;
477}
478
Martijn Coenencf5916f2020-01-03 14:36:45 +0100479void VolumeManager::createPendingDisksIfNeeded() {
480 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
481 if (!mSecureKeyguardShowing && userZeroStarted) {
482 // Now that secure keyguard has been dismissed and user 0 has
483 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700484 for (const auto& disk : mPendingDisks) {
485 disk->create();
486 mDisks.push_back(disk);
487 }
488 mPendingDisks.clear();
489 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100490}
491
492int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
493 mSecureKeyguardShowing = isShowing;
494 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700495 return 0;
496}
497
Narayan Kamath02efdf52019-11-27 10:53:51 +0000498// This code is executed after a fork so it's very important that the set of
499// methods we call here is strictly limited.
500//
501// TODO: Get rid of this guesswork altogether and instead exec a process
502// immediately after fork to do our bindding for us.
503static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000504 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000505 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000506 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000507 strerror(errno));
508 return false;
509 }
510
511 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
512 // to also protect against future changes that may cause issues across a
513 // fork.
514 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
515 errno != ENOENT) {
516 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
517 strerror(errno));
518 return false;
519 }
520
521 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
522 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000523 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000524 return false;
525 }
526
527 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
528 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000529 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000530 strerror(errno));
531 return false;
532 }
533
534 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
535 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000536 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000537 return false;
538 }
539
540 return true;
541}
542
Ricky Wai07e64a42020-02-11 14:31:24 +0000543// Fork the process and remount storage
544bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
545 int32_t mountMode = *static_cast<int32_t*>(params);
546 std::string userSource;
547 std::string storageSource;
548 pid_t child;
549 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800550 switch (mountMode) {
551 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000552 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800553 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000554 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800555 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000556 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700557 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000558 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800559 break;
Zim981222f2019-09-09 10:24:44 +0100560 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000561 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800562 default:
563 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000564 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800565 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000566 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700567
Ricky Wai07e64a42020-02-11 14:31:24 +0000568 // Fork a child to mount user-specific symlink helper into place
569 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
570 if (!(child = fork())) {
571 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
572 _exit(0);
573 } else {
574 _exit(1);
575 }
576 }
577
578 if (child == -1) {
579 PLOG(ERROR) << "Failed to fork";
580 return false;
581 } else {
582 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
583 }
584 return true;
585}
586
587// Helper function to scan all processes in /proc and call the callback if:
588// 1). pid belongs to an app process
589// 2). If input uid is 0 or it matches the process uid
590// 3). If userId is not -1 or userId matches the process userId
591bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700592 DIR* dir;
593 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600594 std::string rootName;
595 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700596 int pidFd;
597 int nsFd;
598 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700599
Jiyong Park8d21c922019-01-04 13:35:25 +0900600 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
601
Jeff Sharkey66270a22015-06-24 11:49:24 -0700602 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000603 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
604 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700605 }
606
607 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600608 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000609 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700610 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000611 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700612 }
613
Ricky Wai07e64a42020-02-11 14:31:24 +0000614 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700615 // Poke through all running PIDs look for apps running as UID
616 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700617 pid_t pid;
618 if (de->d_type != DT_DIR) continue;
619 if (!android::base::ParseInt(de->d_name, &pid)) continue;
620
Jeff Sharkey66270a22015-06-24 11:49:24 -0700621 pidFd = -1;
622 nsFd = -1;
623
624 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
625 if (pidFd < 0) {
626 goto next;
627 }
628 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000629 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700630 goto next;
631 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000632 if (uid != 0 && sb.st_uid != uid) {
633 goto next;
634 }
635 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700636 goto next;
637 }
638
639 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600640 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000641 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
642 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700643 goto next;
644 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600645 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700646 goto next;
647 }
648
Jiyong Park8d21c922019-01-04 13:35:25 +0900649 if (apexUpdatable) {
650 std::string exeName;
651 // When ro.apex.bionic_updatable is set to true,
652 // some early native processes have mount namespaces that are different
653 // from that of the init. Therefore, above check can't filter them out.
654 // Since the propagation type of / is 'shared', unmounting /storage
655 // for the early native processes affects other processes including
656 // init. Filter out such processes by skipping if a process is a
657 // non-Java process whose UID is < AID_APP_START. (The UID condition
658 // is required to not filter out child processes spawned by apps.)
659 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900660 goto next;
661 }
662 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900663 goto next;
664 }
665 }
666
Jeff Sharkey66270a22015-06-24 11:49:24 -0700667 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700668 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
669 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700670 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000671 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
672 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700673 goto next;
674 }
675
Ricky Wai07e64a42020-02-11 14:31:24 +0000676 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
677 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700678 }
679
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700680 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700681 close(nsFd);
682 close(pidFd);
683 }
684 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000685 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
686 return true;
687}
688
Ricky Waia2ca11e2021-01-15 14:03:23 +0000689// In each app's namespace, unmount obb and data dirs
690static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
691 int uid, const char* targets[], int size) {
692 // This code is executed after a fork so it's very important that the set of
693 // methods we call here is strictly limited.
694 if (setns(nsFd, CLONE_NEWNS) != 0) {
695 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
696 return false;
697 }
698
699 // Unmount of Android/data/foo needs to be done before Android/data below.
700 bool result = true;
701 for (int i = 0; i < size; i++) {
702 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
703 errno != ENOENT) {
704 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
705 targets[i], strerror(errno));
706 result = false;
707 }
708 }
709
710 // Mount tmpfs on Android/data and Android/obb
711 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
712 errno != ENOENT) {
713 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
714 android_data_dir, strerror(errno));
715 result = false;
716 }
717 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
718 errno != ENOENT) {
719 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
720 android_obb_dir, strerror(errno));
721 result = false;
722 }
723 return result;
724}
725
Ricky Waie96b34f2020-05-07 16:01:33 +0100726// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
727// package dirs.
728static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
729 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000730 // This code is executed after a fork so it's very important that the set of
731 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000732 if (setns(nsFd, CLONE_NEWNS) != 0) {
733 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
734 return false;
735 }
736
Ricky Waie96b34f2020-05-07 16:01:33 +0100737 // Mount tmpfs on Android/data and Android/obb
738 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
739 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
740 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
741 android_data_dir, strerror(errno));
742 return false;
743 }
744 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
745 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
746 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
747 android_obb_dir, strerror(errno));
748 return false;
749 }
750
Ricky Wai6b122572020-02-28 16:30:47 +0000751 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100752 // Create package dir and bind mount it to the actual one.
753 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
754 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
755 targets[i], strerror(errno));
756 return false;
757 }
Ricky Wai6b122572020-02-28 16:30:47 +0000758 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
759 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
760 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000761 return false;
762 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000763 }
764 return true;
765}
766
Ricky Wai6b122572020-02-28 16:30:47 +0000767static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
768 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700769 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000770 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
771 userId, dirName.c_str(), packageName.c_str());
772 } else {
773 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
774 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000775 }
Ricky Wai6b122572020-02-28 16:30:47 +0000776}
777
778static std::string getStorageDirTarget(userid_t userId, std::string dirName,
779 std::string packageName) {
780 return StringPrintf("/storage/emulated/%d/%s/%s",
781 userId, dirName.c_str(), packageName.c_str());
782}
783
Ricky Waia2ca11e2021-01-15 14:03:23 +0000784// Fork the process and remount / unmount app data and obb dirs
785bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000786 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000787 userid_t userId = multiuser_get_user_id(uid);
788 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
789 android::base::unique_fd nsFd(
790 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
791 if (nsFd == -1) {
792 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
793 return false;
794 }
795 // Storing both Android/obb and Android/data paths.
796 int size = packageNames.size() * 2;
797
798 std::unique_ptr<std::string[]> sources(new std::string[size]);
799 std::unique_ptr<std::string[]> targets(new std::string[size]);
800 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
801 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
802 const char** sources_cstr = sources_uptr.get();
803 const char** targets_cstr = targets_uptr.get();
804
805 for (int i = 0; i < size; i += 2) {
806 std::string const& packageName = packageNames[i/2];
807 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
808 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
809 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
810 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
811
812 sources_cstr[i] = sources[i].c_str();
813 targets_cstr[i] = targets[i].c_str();
814 sources_cstr[i+1] = sources[i+1].c_str();
815 targets_cstr[i+1] = targets[i+1].c_str();
816 }
817
818 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000819 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000820 // This needs to be done before EnsureDirExists to ensure Android/ is created.
821 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000822 if (status != OK) {
823 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
824 return false;
825 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000826 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
827 if (status != OK) {
828 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
829 return false;
830 }
Ricky Wai6b122572020-02-28 16:30:47 +0000831 }
832
Ricky Waie96b34f2020-05-07 16:01:33 +0100833 char android_data_dir[PATH_MAX];
834 char android_obb_dir[PATH_MAX];
835 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
836 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
837
Ricky Wai6b122572020-02-28 16:30:47 +0000838 pid_t child;
839 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
840 // original vold process mount namespace.
841 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000842 if (doUnmount) {
843 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
844 targets_cstr, size)) {
845 _exit(0);
846 } else {
847 _exit(1);
848 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000849 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000850 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
851 sources_cstr, targets_cstr, size)) {
852 _exit(0);
853 } else {
854 _exit(1);
855 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000856 }
857 }
Ricky Wai6b122572020-02-28 16:30:47 +0000858
Ricky Wai07e64a42020-02-11 14:31:24 +0000859 if (child == -1) {
860 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000861 return false;
862 } else {
863 int status;
864 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
865 PLOG(ERROR) << "Failed to waitpid: " << child;
866 return false;
867 }
868 if (!WIFEXITED(status)) {
869 PLOG(ERROR) << "Process did not exit normally, status: " << status;
870 return false;
871 }
872 if (WEXITSTATUS(status)) {
873 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
874 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000875 }
876 }
Ricky Wai6b122572020-02-28 16:30:47 +0000877 return true;
878}
879
Ricky Waia2ca11e2021-01-15 14:03:23 +0000880int VolumeManager::handleAppStorageDirs(int uid, int pid,
881 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000882 // Only run the remount if fuse is mounted for that user.
883 userid_t userId = multiuser_get_user_id(uid);
884 bool fuseMounted = false;
885 for (auto& vol : mInternalEmulatedVolumes) {
886 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
887 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
888 if (emulatedVol) {
889 fuseMounted = emulatedVol->isFuseMounted();
890 }
891 break;
892 }
893 }
894 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000895 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000896 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700897 return 0;
898}
899
Martijn Coenen23c04452020-04-29 07:49:41 +0200900int VolumeManager::abortFuse() {
901 return android::vold::AbortFuseConnections();
902}
903
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700904int VolumeManager::reset() {
905 // Tear down all existing disks/volumes and start from a blank slate so
906 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100907 for (const auto& vol : mInternalEmulatedVolumes) {
908 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800909 }
Zima438b242019-09-25 14:37:38 +0100910 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100911
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900912 // Destroy and recreate all disks except that StubVolume disks are just
913 // destroyed and removed from both mDisks and mPendingDisks.
914 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
915 // their disk recreation on reset events should be handled from outside by
916 // calling createStubVolume() again.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700917 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700918 disk->destroy();
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900919 if (!disk->isStub()) {
920 disk->create();
921 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700922 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900923 const auto isStub = [](const auto& disk) { return disk->isStub(); };
924 mDisks.remove_if(isStub);
925 mPendingDisks.remove_if(isStub);
926
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600927 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700928 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800929 mStartedUsers.clear();
Martijn Coenen73e30102022-07-12 08:11:02 +0000930 mSharedStorageUser.clear();
Zim817f2242022-05-19 16:53:22 +0100931
932 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
933 // with FUSE fds open.
934 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700935 return 0;
936}
937
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700938// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700939int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100940 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700941 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700942 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700943 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100944 for (const auto& vol : mInternalEmulatedVolumes) {
945 vol->destroy();
946 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700947 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700948 disk->destroy();
949 }
Zima438b242019-09-25 14:37:38 +0100950
951 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700952 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700953 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700954 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200955
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700956 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700957}
958
Jeff Sharkey9c484982015-03-31 10:35:33 -0700959int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700960 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600961 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700962
Jeff Sharkey9c484982015-03-31 10:35:33 -0700963 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100964 for (const auto& vol : mInternalEmulatedVolumes) {
965 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700966 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700967 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700968 disk->unmountAll();
969 }
970
971 // Worst case we might have some stale mounts lurking around, so
972 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800973 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700974 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600975 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700976 return -errno;
977 }
978
979 // Some volumes can be stacked on each other, so force unmount in
980 // reverse order to give us the best chance of success.
981 std::list<std::string> toUnmount;
982 mntent* mentry;
983 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600984 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700985 if ((StartsWith(test, "/mnt/") &&
986#ifdef __ANDROID_DEBUGGABLE__
987 !StartsWith(test, "/mnt/scratch") &&
988#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100989 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100990 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700991 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600992 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700993 }
994 }
995 endmntent(fp);
996
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700997 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600998 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700999 android::vold::ForceUnmount(path);
1000 }
1001
1002 return 0;
1003}
1004
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001005int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001006 int size = paths.size();
1007 for (int i = 0; i < size; i++) {
1008 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1009 true /* skipIfDirExists */);
1010 if (result != OK) {
1011 return result;
1012 }
1013 }
1014 return OK;
1015}
1016
1017int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1018 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001019 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001020 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001021 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001022 return -EINVAL;
1023 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001024
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001025 // Find the volume it belongs to
1026 auto filter_fn = [&](const VolumeBase& vol) {
1027 if (vol.getState() != VolumeBase::State::kMounted) {
1028 // The volume must be mounted
1029 return false;
1030 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001031 if (!vol.isVisibleForWrite()) {
1032 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001033 return false;
1034 }
1035 if (vol.getInternalPath().empty()) {
1036 return false;
1037 }
1038 if (vol.getMountUserId() != USER_UNKNOWN &&
1039 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1040 // The app dir must be created on a volume with the same user-id
1041 return false;
1042 }
1043 if (!path.empty() && StartsWith(path, vol.getPath())) {
1044 return true;
1045 }
1046
1047 return false;
1048 };
1049 auto volume = findVolumeWithFilter(filter_fn);
1050 if (volume == nullptr) {
1051 LOG(ERROR) << "Failed to find mounted volume for " << path;
1052 return -EINVAL;
1053 }
Zimc59d7742020-01-06 21:48:16 +00001054 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1055 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1056 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1057 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001058 const std::string lowerPath =
1059 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001060
Martijn Coenen62a4b272020-01-31 15:23:09 +01001061 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1062
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001063 const int access_result = access(lowerPath.c_str(), F_OK);
1064 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001065 // Nothing to fixup
1066 return OK;
1067 }
1068
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001069 if (skipIfDirExists && access_result == 0) {
1070 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1071 // which the dir doesn't need to have correct permission for now yet.
1072 return OK;
1073 }
1074
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001075 if (volume->getType() == VolumeBase::Type::kPublic) {
1076 // On public volumes, we don't need to setup permissions, as everything goes through
1077 // FUSE; just create the dirs and be done with it.
1078 return fs_mkdirs(lowerPath.c_str(), 0700);
1079 }
1080
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001081 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001082 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1083}
1084
1085int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001086 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001087 //sdcardfs magically does this for us
1088 return OK;
1089 }
1090 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001091}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001092
Eric Biggers7e79a432022-03-01 21:19:18 +00001093int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1094 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001095 int id = mNextObbId++;
1096
Martijn Coenend6a612a2020-11-19 10:49:45 +01001097 std::string lowerSourcePath;
1098
1099 // Convert to lower filesystem path
1100 if (StartsWith(sourcePath, "/storage/")) {
1101 auto filter_fn = [&](const VolumeBase& vol) {
1102 if (vol.getState() != VolumeBase::State::kMounted) {
1103 // The volume must be mounted
1104 return false;
1105 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001106 if (!vol.isVisibleForWrite()) {
1107 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001108 return false;
1109 }
1110 if (vol.getInternalPath().empty()) {
1111 return false;
1112 }
1113 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1114 return true;
1115 }
1116
1117 return false;
1118 };
1119 auto volume = findVolumeWithFilter(filter_fn);
1120 if (volume == nullptr) {
1121 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1122 return -EINVAL;
1123 } else {
1124 lowerSourcePath =
1125 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1126 }
1127 } else {
1128 lowerSourcePath = sourcePath;
1129 }
1130
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001131 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001132 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001133 vol->create();
1134
1135 mObbVolumes.push_back(vol);
1136 *outVolId = vol->getId();
1137 return android::OK;
1138}
1139
1140int VolumeManager::destroyObb(const std::string& volId) {
1141 auto i = mObbVolumes.begin();
1142 while (i != mObbVolumes.end()) {
1143 if ((*i)->getId() == volId) {
1144 (*i)->destroy();
1145 i = mObbVolumes.erase(i);
1146 } else {
1147 ++i;
1148 }
1149 }
1150 return android::OK;
1151}
1152
Risan8c9f3322018-10-29 08:52:56 +09001153int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1154 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001155 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001156 std::string* outVolId) {
1157 dev_t stubId = --mNextStubId;
1158 auto vol = std::shared_ptr<android::vold::StubVolume>(
1159 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001160
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001161 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001162 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1163 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001164 if (flags & android::vold::Disk::Flags::kStubVisible) {
1165 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1166 } else {
1167 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1168 }
Risan82e90de2020-02-04 16:07:21 +09001169 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001170 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001171 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001172 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001173 disk->initializePartition(vol);
1174 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001175 *outVolId = vol->getId();
1176 return android::OK;
1177}
1178
1179int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001180 auto tokens = android::base::Split(volId, ":");
1181 CHECK(tokens.size() == 2);
1182 dev_t stubId;
1183 CHECK(android::base::ParseUint(tokens[1], &stubId));
1184 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001185 return android::OK;
1186}
1187
Risan8f6198d2018-10-26 20:56:45 -06001188int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001189 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001190}
1191
Risan8f6198d2018-10-26 20:56:45 -06001192int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001193 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001194}
1195
1196int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001197 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001198}