blob: 8190e7e9cf25740c808fc0eb3c6ea739fe7ad9de [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
Tom Marshall34e1e5d2015-11-04 15:44:44 -0800230 android::vold::Disk* disk = (source->getPartNum() == -1) ?
231 new android::vold::Disk(eventPath, device,
232 source->getNickname(), flags) :
233 new android::vold::DiskPartition(eventPath, device,
234 source->getNickname(), flags,
Tom Marshall9f8b4682015-11-05 11:20:54 -0800235 source->getPartNum(),
236 source->getFsType(), source->getMntOpts());
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700237 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
238 break;
239 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700240 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700241 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700242 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700243 case NetlinkEvent::Action::kChange: {
Nikita Ioffeb881fc42021-07-28 02:58:57 +0100244 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700245 handleDiskChanged(device);
246 break;
247 }
248 case NetlinkEvent::Action::kRemove: {
249 handleDiskRemoved(device);
250 break;
251 }
252 default: {
253 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
254 break;
255 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700256 }
257}
258
Jeff Sharkey401b2602017-12-14 22:15:20 -0700259void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
260 // For security reasons, if secure keyguard is showing, wait
261 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100262 // Additionally, wait until user 0 is actually started, since we need
263 // the user to be up before we can mount a FUSE daemon to handle the disk.
264 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700265 if (mSecureKeyguardShowing) {
266 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700267 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700268 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100269 } else if (!userZeroStarted) {
270 LOG(INFO) << "Found disk at " << disk->getEventPath()
271 << " but delaying scan due to user zero not having started";
272 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700273 } else {
274 disk->create();
275 mDisks.push_back(disk);
276 }
277}
278
279void VolumeManager::handleDiskChanged(dev_t device) {
280 for (const auto& disk : mDisks) {
281 if (disk->getDevice() == device) {
282 disk->readMetadata();
283 disk->readPartitions();
284 }
285 }
286
287 // For security reasons, we ignore all pending disks, since
288 // we'll scan them once the device is unlocked
289}
290
291void VolumeManager::handleDiskRemoved(dev_t device) {
292 auto i = mDisks.begin();
293 while (i != mDisks.end()) {
294 if ((*i)->getDevice() == device) {
295 (*i)->destroy();
296 i = mDisks.erase(i);
297 } else {
298 ++i;
299 }
300 }
301 auto j = mPendingDisks.begin();
302 while (j != mPendingDisks.end()) {
303 if ((*j)->getDevice() == device) {
304 j = mPendingDisks.erase(j);
305 } else {
306 ++j;
307 }
308 }
309}
310
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700311void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800312 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700313 mDiskSources.push_back(diskSource);
314}
315
316std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
317 for (auto disk : mDisks) {
318 if (disk->getId() == id) {
319 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700320 }
321 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700322 return nullptr;
323}
San Mehatf1b736b2009-10-10 17:22:08 -0700324
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700325std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100326 for (const auto& vol : mInternalEmulatedVolumes) {
327 if (vol->getId() == id) {
328 return vol;
329 }
San Mehatf1b736b2009-10-10 17:22:08 -0700330 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700331 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700332 auto vol = disk->findVolume(id);
333 if (vol != nullptr) {
334 return vol;
335 }
336 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600337 for (const auto& vol : mObbVolumes) {
338 if (vol->getId() == id) {
339 return vol;
340 }
341 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700342 return nullptr;
343}
344
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800345void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
346 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700347 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700348 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700349 disk->listVolumes(type, list);
350 }
351}
352
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600353int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700354 std::string normalizedGuid;
355 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
356 LOG(WARNING) << "Invalid GUID " << partGuid;
357 return -1;
358 }
359
Paul Crowleyc6433a22017-10-24 14:54:43 -0700360 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700361 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
362 if (unlink(keyPath.c_str()) != 0) {
363 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700364 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700365 }
Eric Biggersa701c452018-10-23 13:06:55 -0700366 if (fscrypt_is_native()) {
367 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700368 success = false;
369 }
370 }
371 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700372}
373
Zima438b242019-09-25 14:37:38 +0100374void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
375 // Destroy and remove all unstacked EmulatedVolumes for the user
376 auto i = mInternalEmulatedVolumes.begin();
377 while (i != mInternalEmulatedVolumes.end()) {
378 auto vol = *i;
379 if (vol->getMountUserId() == userId) {
380 vol->destroy();
381 i = mInternalEmulatedVolumes.erase(i);
382 } else {
383 i++;
384 }
385 }
386
387 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
388 std::list<std::string> private_vols;
389 listVolumes(VolumeBase::Type::kPrivate, private_vols);
390 for (const std::string& id : private_vols) {
391 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
392 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
393 if (pvol->getState() == VolumeBase::State::kMounted) {
394 for (const auto& vol : pvol->getVolumes()) {
395 if (vol->getMountUserId() == userId) {
396 vols_to_remove.push_back(vol);
397 }
398 }
399 for (const auto& vol : vols_to_remove) {
400 vol->destroy();
401 pvol->removeVolume(vol);
402 }
403 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
404 }
405}
406
407void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
408 // Create unstacked EmulatedVolumes for the user
409 auto vol = std::shared_ptr<android::vold::VolumeBase>(
410 new android::vold::EmulatedVolume("/data/media", userId));
411 vol->setMountUserId(userId);
412 mInternalEmulatedVolumes.push_back(vol);
413 vol->create();
414
415 // Create stacked EmulatedVolumes for the user on each PrivateVolume
416 std::list<std::string> private_vols;
417 listVolumes(VolumeBase::Type::kPrivate, private_vols);
418 for (const std::string& id : private_vols) {
419 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
420 if (pvol->getState() == VolumeBase::State::kMounted) {
421 auto evol =
422 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
423 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
424 userId));
425 evol->setMountUserId(userId);
426 pvol->addVolume(evol);
427 evol->create();
428 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
429 }
430}
431
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700432int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100433 LOG(INFO) << "onUserAdded: " << userId;
434
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700435 mAddedUsers[userId] = userSerialNumber;
436 return 0;
437}
438
439int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100440 LOG(INFO) << "onUserRemoved: " << userId;
441
Zim2d45d9b2019-11-14 16:19:05 +0000442 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700443 mAddedUsers.erase(userId);
444 return 0;
445}
446
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700447int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100448 LOG(INFO) << "onUserStarted: " << userId;
449
Zim2d45d9b2019-11-14 16:19:05 +0000450 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
451 createEmulatedVolumesForUser(userId);
452 }
453
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700454 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100455
456 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700457 return 0;
458}
459
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700460int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700461 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100462
Zim2d45d9b2019-11-14 16:19:05 +0000463 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100464 destroyEmulatedVolumesForUser(userId);
465 }
466
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700467 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700468 return 0;
469}
470
Martijn Coenencf5916f2020-01-03 14:36:45 +0100471void VolumeManager::createPendingDisksIfNeeded() {
472 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
473 if (!mSecureKeyguardShowing && userZeroStarted) {
474 // Now that secure keyguard has been dismissed and user 0 has
475 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700476 for (const auto& disk : mPendingDisks) {
477 disk->create();
478 mDisks.push_back(disk);
479 }
480 mPendingDisks.clear();
481 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100482}
483
484int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
485 mSecureKeyguardShowing = isShowing;
486 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700487 return 0;
488}
489
Narayan Kamath02efdf52019-11-27 10:53:51 +0000490// This code is executed after a fork so it's very important that the set of
491// methods we call here is strictly limited.
492//
493// TODO: Get rid of this guesswork altogether and instead exec a process
494// immediately after fork to do our bindding for us.
495static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
Ricky Wai07e64a42020-02-11 14:31:24 +0000496 const char* name) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000497 if (setns(nsFd, CLONE_NEWNS) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000498 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000499 strerror(errno));
500 return false;
501 }
502
503 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
504 // to also protect against future changes that may cause issues across a
505 // fork.
506 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
507 errno != ENOENT) {
508 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
509 strerror(errno));
510 return false;
511 }
512
513 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
514 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000515 storageSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000516 return false;
517 }
518
519 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
520 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
Ricky Wai07e64a42020-02-11 14:31:24 +0000521 "Failed to set MS_SLAVE to /storage for %s :%s", name,
Narayan Kamath02efdf52019-11-27 10:53:51 +0000522 strerror(errno));
523 return false;
524 }
525
526 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
527 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
Ricky Wai07e64a42020-02-11 14:31:24 +0000528 userSource, name, strerror(errno));
Narayan Kamath02efdf52019-11-27 10:53:51 +0000529 return false;
530 }
531
532 return true;
533}
534
Ricky Wai07e64a42020-02-11 14:31:24 +0000535// Fork the process and remount storage
536bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
537 int32_t mountMode = *static_cast<int32_t*>(params);
538 std::string userSource;
539 std::string storageSource;
540 pid_t child;
541 // Need to fix these paths to account for when sdcardfs is gone
Sudheer Shanka817b9112018-12-13 17:40:28 -0800542 switch (mountMode) {
543 case VoldNativeService::REMOUNT_MODE_NONE:
Ricky Wai07e64a42020-02-11 14:31:24 +0000544 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800545 case VoldNativeService::REMOUNT_MODE_DEFAULT:
Ricky Wai07e64a42020-02-11 14:31:24 +0000546 storageSource = "/mnt/runtime/default";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800547 break;
Abhijeet Kaure715ec12021-02-24 12:33:25 +0000548 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700549 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Ricky Wai07e64a42020-02-11 14:31:24 +0000550 storageSource = "/mnt/runtime/write";
Sudheer Shanka817b9112018-12-13 17:40:28 -0800551 break;
Zim981222f2019-09-09 10:24:44 +0100552 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
Ricky Wai07e64a42020-02-11 14:31:24 +0000553 return true;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800554 default:
555 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
Ricky Wai07e64a42020-02-11 14:31:24 +0000556 return false;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800557 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000558 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700559
Ricky Wai07e64a42020-02-11 14:31:24 +0000560 // Fork a child to mount user-specific symlink helper into place
561 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
562 if (!(child = fork())) {
563 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
564 _exit(0);
565 } else {
566 _exit(1);
567 }
568 }
569
570 if (child == -1) {
571 PLOG(ERROR) << "Failed to fork";
572 return false;
573 } else {
574 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
575 }
576 return true;
577}
578
579// Helper function to scan all processes in /proc and call the callback if:
580// 1). pid belongs to an app process
581// 2). If input uid is 0 or it matches the process uid
582// 3). If userId is not -1 or userId matches the process userId
583bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700584 DIR* dir;
585 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600586 std::string rootName;
587 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700588 int pidFd;
589 int nsFd;
590 struct stat sb;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700591
Jiyong Park8d21c922019-01-04 13:35:25 +0900592 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
593
Jeff Sharkey66270a22015-06-24 11:49:24 -0700594 if (!(dir = opendir("/proc"))) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000595 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
596 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700597 }
598
599 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600600 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000601 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700602 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000603 return false;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700604 }
605
Ricky Wai07e64a42020-02-11 14:31:24 +0000606 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700607 // Poke through all running PIDs look for apps running as UID
608 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700609 pid_t pid;
610 if (de->d_type != DT_DIR) continue;
611 if (!android::base::ParseInt(de->d_name, &pid)) continue;
612
Jeff Sharkey66270a22015-06-24 11:49:24 -0700613 pidFd = -1;
614 nsFd = -1;
615
616 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
617 if (pidFd < 0) {
618 goto next;
619 }
620 if (fstat(pidFd, &sb) != 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000621 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700622 goto next;
623 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000624 if (uid != 0 && sb.st_uid != uid) {
625 goto next;
626 }
627 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700628 goto next;
629 }
630
631 // Matches so far, but refuse to touch if in root namespace
Jeff Sharkey3472e522017-10-06 18:02:53 -0600632 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000633 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
634 "Failed to read namespacefor %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700635 goto next;
636 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600637 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700638 goto next;
639 }
640
Jiyong Park8d21c922019-01-04 13:35:25 +0900641 if (apexUpdatable) {
642 std::string exeName;
643 // When ro.apex.bionic_updatable is set to true,
644 // some early native processes have mount namespaces that are different
645 // from that of the init. Therefore, above check can't filter them out.
646 // Since the propagation type of / is 'shared', unmounting /storage
647 // for the early native processes affects other processes including
648 // init. Filter out such processes by skipping if a process is a
649 // non-Java process whose UID is < AID_APP_START. (The UID condition
650 // is required to not filter out child processes spawned by apps.)
651 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900652 goto next;
653 }
654 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
Jiyong Park8d21c922019-01-04 13:35:25 +0900655 goto next;
656 }
657 }
658
Jeff Sharkey66270a22015-06-24 11:49:24 -0700659 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700660 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
661 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700662 if (nsFd < 0) {
Ricky Wai07e64a42020-02-11 14:31:24 +0000663 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
664 "Failed to open namespace for %s", de->d_name);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700665 goto next;
666 }
667
Ricky Wai07e64a42020-02-11 14:31:24 +0000668 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
669 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700670 }
671
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700672 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700673 close(nsFd);
674 close(pidFd);
675 }
676 closedir(dir);
Ricky Wai07e64a42020-02-11 14:31:24 +0000677 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
678 return true;
679}
680
Ricky Waia2ca11e2021-01-15 14:03:23 +0000681// In each app's namespace, unmount obb and data dirs
682static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
683 int uid, const char* targets[], int size) {
684 // This code is executed after a fork so it's very important that the set of
685 // methods we call here is strictly limited.
686 if (setns(nsFd, CLONE_NEWNS) != 0) {
687 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
688 return false;
689 }
690
691 // Unmount of Android/data/foo needs to be done before Android/data below.
692 bool result = true;
693 for (int i = 0; i < size; i++) {
694 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
695 errno != ENOENT) {
696 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
697 targets[i], strerror(errno));
698 result = false;
699 }
700 }
701
702 // Mount tmpfs on Android/data and Android/obb
703 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
704 errno != ENOENT) {
705 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
706 android_data_dir, strerror(errno));
707 result = false;
708 }
709 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
710 errno != ENOENT) {
711 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
712 android_obb_dir, strerror(errno));
713 result = false;
714 }
715 return result;
716}
717
Ricky Waie96b34f2020-05-07 16:01:33 +0100718// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
719// package dirs.
720static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
721 int uid, const char* sources[], const char* targets[], int size) {
Ricky Wai6b122572020-02-28 16:30:47 +0000722 // This code is executed after a fork so it's very important that the set of
723 // methods we call here is strictly limited.
Ricky Wai07e64a42020-02-11 14:31:24 +0000724 if (setns(nsFd, CLONE_NEWNS) != 0) {
725 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
726 return false;
727 }
728
Ricky Waie96b34f2020-05-07 16:01:33 +0100729 // Mount tmpfs on Android/data and Android/obb
730 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
731 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
732 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
733 android_data_dir, strerror(errno));
734 return false;
735 }
736 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
737 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
738 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
739 android_obb_dir, strerror(errno));
740 return false;
741 }
742
Ricky Wai6b122572020-02-28 16:30:47 +0000743 for (int i = 0; i < size; i++) {
Ricky Waie96b34f2020-05-07 16:01:33 +0100744 // Create package dir and bind mount it to the actual one.
745 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
746 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
747 targets[i], strerror(errno));
748 return false;
749 }
Ricky Wai6b122572020-02-28 16:30:47 +0000750 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
751 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
752 sources[i], targets[i], strerror(errno));
Ricky Wai07e64a42020-02-11 14:31:24 +0000753 return false;
754 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000755 }
756 return true;
757}
758
Ricky Wai6b122572020-02-28 16:30:47 +0000759static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
760 const std::string& packageName) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -0700761 if (IsSdcardfsUsed()) {
Ricky Wai6b122572020-02-28 16:30:47 +0000762 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
763 userId, dirName.c_str(), packageName.c_str());
764 } else {
765 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
766 userId, userId, dirName.c_str(), packageName.c_str());
Ricky Wai07e64a42020-02-11 14:31:24 +0000767 }
Ricky Wai6b122572020-02-28 16:30:47 +0000768}
769
770static std::string getStorageDirTarget(userid_t userId, std::string dirName,
771 std::string packageName) {
772 return StringPrintf("/storage/emulated/%d/%s/%s",
773 userId, dirName.c_str(), packageName.c_str());
774}
775
Ricky Waia2ca11e2021-01-15 14:03:23 +0000776// Fork the process and remount / unmount app data and obb dirs
777bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000778 const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000779 userid_t userId = multiuser_get_user_id(uid);
780 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
781 android::base::unique_fd nsFd(
782 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
783 if (nsFd == -1) {
784 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
785 return false;
786 }
787 // Storing both Android/obb and Android/data paths.
788 int size = packageNames.size() * 2;
789
790 std::unique_ptr<std::string[]> sources(new std::string[size]);
791 std::unique_ptr<std::string[]> targets(new std::string[size]);
792 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
793 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
794 const char** sources_cstr = sources_uptr.get();
795 const char** targets_cstr = targets_uptr.get();
796
797 for (int i = 0; i < size; i += 2) {
798 std::string const& packageName = packageNames[i/2];
799 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
800 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
801 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
802 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
803
804 sources_cstr[i] = sources[i].c_str();
805 targets_cstr[i] = targets[i].c_str();
806 sources_cstr[i+1] = sources[i+1].c_str();
807 targets_cstr[i+1] = targets[i+1].c_str();
808 }
809
810 for (int i = 0; i < size; i++) {
Linus Tufvesson75973cb2020-03-23 11:59:43 +0000811 // Make sure /storage/emulated/... paths are setup correctly
Ricky Waif6da79c2021-01-19 11:27:36 +0000812 // This needs to be done before EnsureDirExists to ensure Android/ is created.
813 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
Ricky Wai6b122572020-02-28 16:30:47 +0000814 if (status != OK) {
815 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
816 return false;
817 }
Ricky Waif6da79c2021-01-19 11:27:36 +0000818 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
819 if (status != OK) {
820 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
821 return false;
822 }
Ricky Wai6b122572020-02-28 16:30:47 +0000823 }
824
Ricky Waie96b34f2020-05-07 16:01:33 +0100825 char android_data_dir[PATH_MAX];
826 char android_obb_dir[PATH_MAX];
827 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
828 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
829
Ricky Wai6b122572020-02-28 16:30:47 +0000830 pid_t child;
831 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
832 // original vold process mount namespace.
833 if (!(child = fork())) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000834 if (doUnmount) {
835 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
836 targets_cstr, size)) {
837 _exit(0);
838 } else {
839 _exit(1);
840 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000841 } else {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000842 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
843 sources_cstr, targets_cstr, size)) {
844 _exit(0);
845 } else {
846 _exit(1);
847 }
Ricky Wai07e64a42020-02-11 14:31:24 +0000848 }
849 }
Ricky Wai6b122572020-02-28 16:30:47 +0000850
Ricky Wai07e64a42020-02-11 14:31:24 +0000851 if (child == -1) {
852 PLOG(ERROR) << "Failed to fork";
Ricky Wai6b122572020-02-28 16:30:47 +0000853 return false;
854 } else {
855 int status;
856 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
857 PLOG(ERROR) << "Failed to waitpid: " << child;
858 return false;
859 }
860 if (!WIFEXITED(status)) {
861 PLOG(ERROR) << "Process did not exit normally, status: " << status;
862 return false;
863 }
864 if (WEXITSTATUS(status)) {
865 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
866 return false;
Ricky Wai07e64a42020-02-11 14:31:24 +0000867 }
868 }
Ricky Wai6b122572020-02-28 16:30:47 +0000869 return true;
870}
871
Ricky Waia2ca11e2021-01-15 14:03:23 +0000872int VolumeManager::handleAppStorageDirs(int uid, int pid,
873 bool doUnmount, const std::vector<std::string>& packageNames) {
Ricky Wai6b122572020-02-28 16:30:47 +0000874 // Only run the remount if fuse is mounted for that user.
875 userid_t userId = multiuser_get_user_id(uid);
876 bool fuseMounted = false;
877 for (auto& vol : mInternalEmulatedVolumes) {
878 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
879 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
880 if (emulatedVol) {
881 fuseMounted = emulatedVol->isFuseMounted();
882 }
883 break;
884 }
885 }
886 if (fuseMounted) {
Ricky Waia2ca11e2021-01-15 14:03:23 +0000887 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
Ricky Wai6b122572020-02-28 16:30:47 +0000888 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700889 return 0;
890}
891
Martijn Coenen23c04452020-04-29 07:49:41 +0200892int VolumeManager::abortFuse() {
893 return android::vold::AbortFuseConnections();
894}
895
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700896int VolumeManager::reset() {
897 // Tear down all existing disks/volumes and start from a blank slate so
898 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100899 for (const auto& vol : mInternalEmulatedVolumes) {
900 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800901 }
Zima438b242019-09-25 14:37:38 +0100902 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100903
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900904 // Destroy and recreate all disks except that StubVolume disks are just
905 // destroyed and removed from both mDisks and mPendingDisks.
906 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
907 // their disk recreation on reset events should be handled from outside by
908 // calling createStubVolume() again.
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700909 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700910 disk->destroy();
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900911 if (!disk->isStub()) {
912 disk->create();
913 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700914 }
Youkichi Hosoidfaff1d2021-11-25 16:24:35 +0900915 const auto isStub = [](const auto& disk) { return disk->isStub(); };
916 mDisks.remove_if(isStub);
917 mPendingDisks.remove_if(isStub);
918
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600919 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700920 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800921 mStartedUsers.clear();
Zim11a666b2022-05-19 16:53:22 +0100922
923 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
924 // with FUSE fds open.
925 abortFuse();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700926 return 0;
927}
928
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700929// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700930int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100931 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700932 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700933 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700934 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100935 for (const auto& vol : mInternalEmulatedVolumes) {
936 vol->destroy();
937 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700938 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700939 disk->destroy();
940 }
Zima438b242019-09-25 14:37:38 +0100941
942 mInternalEmulatedVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700943 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700944 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700945 android::vold::sSleepOnUnmount = true;
Martijn Coenen23c04452020-04-29 07:49:41 +0200946
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700947 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700948}
949
Jeff Sharkey9c484982015-03-31 10:35:33 -0700950int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700951 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600952 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700953
Jeff Sharkey9c484982015-03-31 10:35:33 -0700954 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100955 for (const auto& vol : mInternalEmulatedVolumes) {
956 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700957 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700958 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700959 disk->unmountAll();
960 }
961
962 // Worst case we might have some stale mounts lurking around, so
963 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800964 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700965 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600966 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700967 return -errno;
968 }
969
970 // Some volumes can be stacked on each other, so force unmount in
971 // reverse order to give us the best chance of success.
972 std::list<std::string> toUnmount;
973 mntent* mentry;
974 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600975 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700976 if ((StartsWith(test, "/mnt/") &&
977#ifdef __ANDROID_DEBUGGABLE__
978 !StartsWith(test, "/mnt/scratch") &&
979#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100980 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
Ricky Waief639212020-04-07 13:43:20 +0100981 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700982 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600983 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700984 }
985 }
986 endmntent(fp);
987
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700988 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600989 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700990 android::vold::ForceUnmount(path);
991 }
992
993 return 0;
994}
995
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000996int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
Ricky Waibbfb6ea2020-12-03 15:32:52 +0000997 int size = paths.size();
998 for (int i = 0; i < size; i++) {
999 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
1000 true /* skipIfDirExists */);
1001 if (result != OK) {
1002 return result;
1003 }
1004 }
1005 return OK;
1006}
1007
1008int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1009 bool skipIfDirExists) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001010 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +01001011 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001012 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001013 return -EINVAL;
1014 }
Martijn Coenen13ff6682019-12-24 12:57:16 +01001015
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001016 // Find the volume it belongs to
1017 auto filter_fn = [&](const VolumeBase& vol) {
1018 if (vol.getState() != VolumeBase::State::kMounted) {
1019 // The volume must be mounted
1020 return false;
1021 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001022 if (!vol.isVisibleForWrite()) {
1023 // App dirs should only be created for writable volumes.
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001024 return false;
1025 }
1026 if (vol.getInternalPath().empty()) {
1027 return false;
1028 }
1029 if (vol.getMountUserId() != USER_UNKNOWN &&
1030 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1031 // The app dir must be created on a volume with the same user-id
1032 return false;
1033 }
1034 if (!path.empty() && StartsWith(path, vol.getPath())) {
1035 return true;
1036 }
1037
1038 return false;
1039 };
1040 auto volume = findVolumeWithFilter(filter_fn);
1041 if (volume == nullptr) {
1042 LOG(ERROR) << "Failed to find mounted volume for " << path;
1043 return -EINVAL;
1044 }
Zimc59d7742020-01-06 21:48:16 +00001045 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1046 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1047 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1048 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +01001049 const std::string lowerPath =
1050 volume->getInternalPath() + path.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +00001051
Martijn Coenen62a4b272020-01-31 15:23:09 +01001052 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1053
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001054 const int access_result = access(lowerPath.c_str(), F_OK);
1055 if (fixupExistingOnly && access_result != 0) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001056 // Nothing to fixup
1057 return OK;
1058 }
1059
Ricky Waibbfb6ea2020-12-03 15:32:52 +00001060 if (skipIfDirExists && access_result == 0) {
1061 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1062 // which the dir doesn't need to have correct permission for now yet.
1063 return OK;
1064 }
1065
Martijn Coenenbf205ab2020-04-20 15:14:48 +02001066 if (volume->getType() == VolumeBase::Type::kPublic) {
1067 // On public volumes, we don't need to setup permissions, as everything goes through
1068 // FUSE; just create the dirs and be done with it.
1069 return fs_mkdirs(lowerPath.c_str(), 0700);
1070 }
1071
Martijn Coenenb5a31c92020-02-13 23:30:38 +01001072 // Create the app paths we need from the root
Martijn Coenen816f4d92020-02-18 15:06:37 +01001073 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1074}
1075
1076int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
Daniel Rosenbergf36bddd2020-05-11 22:58:42 -07001077 if (IsSdcardfsUsed()) {
Martijn Coenen816f4d92020-02-18 15:06:37 +01001078 //sdcardfs magically does this for us
1079 return OK;
1080 }
1081 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001082}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001083
Eric Biggers7e79a432022-03-01 21:19:18 +00001084int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1085 std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001086 int id = mNextObbId++;
1087
Martijn Coenend6a612a2020-11-19 10:49:45 +01001088 std::string lowerSourcePath;
1089
1090 // Convert to lower filesystem path
1091 if (StartsWith(sourcePath, "/storage/")) {
1092 auto filter_fn = [&](const VolumeBase& vol) {
1093 if (vol.getState() != VolumeBase::State::kMounted) {
1094 // The volume must be mounted
1095 return false;
1096 }
Youkichi Hosoi2991cbe2021-11-11 11:23:01 +09001097 if (!vol.isVisibleForWrite()) {
1098 // Obb volume should only be created for writable volumes.
Martijn Coenend6a612a2020-11-19 10:49:45 +01001099 return false;
1100 }
1101 if (vol.getInternalPath().empty()) {
1102 return false;
1103 }
1104 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1105 return true;
1106 }
1107
1108 return false;
1109 };
1110 auto volume = findVolumeWithFilter(filter_fn);
1111 if (volume == nullptr) {
1112 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1113 return -EINVAL;
1114 } else {
1115 lowerSourcePath =
1116 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1117 }
1118 } else {
1119 lowerSourcePath = sourcePath;
1120 }
1121
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001122 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Eric Biggers7e79a432022-03-01 21:19:18 +00001123 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001124 vol->create();
1125
1126 mObbVolumes.push_back(vol);
1127 *outVolId = vol->getId();
1128 return android::OK;
1129}
1130
1131int VolumeManager::destroyObb(const std::string& volId) {
1132 auto i = mObbVolumes.begin();
1133 while (i != mObbVolumes.end()) {
1134 if ((*i)->getId() == volId) {
1135 (*i)->destroy();
1136 i = mObbVolumes.erase(i);
1137 } else {
1138 ++i;
1139 }
1140 }
1141 return android::OK;
1142}
1143
Risan8c9f3322018-10-29 08:52:56 +09001144int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1145 const std::string& fsType, const std::string& fsUuid,
Risan73a7a852020-02-07 18:03:44 +09001146 const std::string& fsLabel, int32_t flags,
Risan82e90de2020-02-04 16:07:21 +09001147 std::string* outVolId) {
1148 dev_t stubId = --mNextStubId;
1149 auto vol = std::shared_ptr<android::vold::StubVolume>(
1150 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
Risan8c9f3322018-10-29 08:52:56 +09001151
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001152 int32_t passedFlags = 0;
Risan73a7a852020-02-07 18:03:44 +09001153 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1154 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
Youkichi Hosoidefc0452020-07-08 06:08:48 +09001155 if (flags & android::vold::Disk::Flags::kStubVisible) {
1156 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1157 } else {
1158 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1159 }
Risan82e90de2020-02-04 16:07:21 +09001160 // StubDisk doesn't have device node corresponds to it. So, a fake device
Risan73a7a852020-02-07 18:03:44 +09001161 // number is used.
Risan82e90de2020-02-04 16:07:21 +09001162 auto disk = std::shared_ptr<android::vold::Disk>(
Risan73a7a852020-02-07 18:03:44 +09001163 new android::vold::Disk("stub", stubId, "stub", passedFlags));
Risan82e90de2020-02-04 16:07:21 +09001164 disk->initializePartition(vol);
1165 handleDiskAdded(disk);
Risan8c9f3322018-10-29 08:52:56 +09001166 *outVolId = vol->getId();
1167 return android::OK;
1168}
1169
1170int VolumeManager::destroyStubVolume(const std::string& volId) {
Risan82e90de2020-02-04 16:07:21 +09001171 auto tokens = android::base::Split(volId, ":");
1172 CHECK(tokens.size() == 2);
1173 dev_t stubId;
1174 CHECK(android::base::ParseUint(tokens[1], &stubId));
1175 handleDiskRemoved(stubId);
Risan8c9f3322018-10-29 08:52:56 +09001176 return android::OK;
1177}
1178
Risan8f6198d2018-10-26 20:56:45 -06001179int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001180 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001181}
1182
Risan8f6198d2018-10-26 20:56:45 -06001183int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001184 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001185}
1186
1187int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001188 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001189}