blob: e6d593a343e7e216e8743c42e724029a662a880e [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>
Yabin Cuid1104f72015-01-02 13:28:28 -080022#include <mntent.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080028#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070029#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070030#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070033#include <array>
San Mehata19b2502010-01-06 10:33:53 -080034
San Mehata2677e42009-12-13 10:40:18 -080035#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070036
Jiyong Park8d21c922019-01-04 13:35:25 +090037#include <ApexProperties.sysprop.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080038#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070039#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060040#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080041#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070042#include <android-base/strings.h>
Narayan Kamath02efdf52019-11-27 10:53:51 +000043#include <async_safe/log.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070044
Jeff Sharkey71ebe152013-09-17 17:24:38 -070045#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060046#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070047
Robert Craigb9e3ba52014-02-04 10:53:00 -050048#include <selinux/android.h>
49
San Mehatfd7f5872009-10-12 11:32:47 -070050#include <sysutils/NetlinkEvent.h>
51
Kenny Root344ca102012-04-03 17:23:01 -070052#include <private/android_filesystem_config.h>
53
Eric Biggersa701c452018-10-23 13:06:55 -070054#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070055
Risanac02a482018-10-31 21:59:47 -060056#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070057#include "Devmapper.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"
66#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070067#include "fs/Ext4.h"
68#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070069#include "model/EmulatedVolume.h"
70#include "model/ObbVolume.h"
Zima438b242019-09-25 14:37:38 +010071#include "model/PrivateVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090072#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080073
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000074using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070075using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070076using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070077using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070078using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060079using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080080using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000081using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080082using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080083using android::vold::DeleteDirContentsAndDir;
Martijn Coenen62a4b272020-01-31 15:23:09 +010084using android::vold::IsFilesystemSupported;
85using android::vold::PrepareAndroidDirs;
86using android::vold::PrepareAppDirsFromRoot;
Zima438b242019-09-25 14:37:38 +010087using android::vold::PrivateVolume;
Sudheer Shanka023b5392019-02-06 12:39:19 -080088using android::vold::Symlink;
89using android::vold::Unlink;
90using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080091using android::vold::VoldNativeService;
Zima438b242019-09-25 14:37:38 +010092using android::vold::VolumeBase;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070093
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060094static const char* kPathUserMount = "/mnt/user";
95static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
96
97static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
98
Sudheer Shanka53947a32018-08-01 10:24:13 -070099static const std::string kEmptyString("");
100
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600101/* 512MiB is large enough for testing purposes */
102static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700103
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700104static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +0800105static const unsigned int kMajorBlockExperimentalMin = 240;
106static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700107
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700108VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700109
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700110VolumeManager* VolumeManager::Instance() {
111 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700112 return sInstance;
113}
114
115VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800116 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600117 mNextObbId = 0;
Risan8c9f3322018-10-29 08:52:56 +0900118 mNextStubVolumeId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700119 // For security reasons, assume that a secure keyguard is
120 // showing until we hear otherwise
121 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700122}
123
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700124VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800125
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600126int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600127 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700128 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129 if (access(kPathVirtualDisk, F_OK) != 0) {
130 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
131 }
132
133 if (mVirtualDisk == nullptr) {
134 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
135 LOG(ERROR) << "Failed to create virtual disk";
136 return -1;
137 }
138
139 struct stat buf;
140 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
141 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
142 return -1;
143 }
144
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700145 auto disk = new android::vold::Disk(
146 "virtual", buf.st_rdev, "virtual",
147 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600148 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700149 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600150 }
151 } else {
152 if (mVirtualDisk != nullptr) {
153 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700154 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600155
156 Loop::destroyByDevice(mVirtualDiskPath.c_str());
157 mVirtualDisk = nullptr;
158 }
159
160 if (access(kPathVirtualDisk, F_OK) == 0) {
161 unlink(kPathVirtualDisk);
162 }
163 }
164 return 0;
165}
166
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700167int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800168 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700169 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800170}
171
San Mehatf1b736b2009-10-10 17:22:08 -0700172int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600173 ATRACE_NAME("VolumeManager::start");
174
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700175 // Always start from a clean slate by unmounting everything in
176 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700177 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700178
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600179 Devmapper::destroyAll();
180 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
198int VolumeManager::stop() {
Zima438b242019-09-25 14:37:38 +0100199 CHECK(!mInternalEmulatedVolumes.empty());
200 for (const auto& vol : mInternalEmulatedVolumes) {
201 vol->destroy();
202 }
203 mInternalEmulatedVolumes.clear();
204
San Mehatf1b736b2009-10-10 17:22:08 -0700205 return 0;
206}
207
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700208void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700209 std::lock_guard<std::mutex> lock(mLock);
210
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700211 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700212 LOG(DEBUG) << "----------------";
213 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700214 evt->dump();
215 }
San Mehatf1b736b2009-10-10 17:22:08 -0700216
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700217 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
218 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700219
220 if (devType != "disk") return;
221
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600222 int major = std::stoi(evt->findParam("MAJOR"));
223 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700224 dev_t device = makedev(major, minor);
225
226 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700227 case NetlinkEvent::Action::kAdd: {
228 for (const auto& source : mDiskSources) {
229 if (source->matches(eventPath)) {
230 // For now, assume that MMC and virtio-blk (the latter is
231 // emulator-specific; see Disk.cpp for details) devices are SD,
232 // and that everything else is USB
233 int flags = source->getFlags();
234 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
235 major >= (int)kMajorBlockExperimentalMin &&
236 major <= (int)kMajorBlockExperimentalMax)) {
237 flags |= android::vold::Disk::Flags::kSd;
238 } else {
239 flags |= android::vold::Disk::Flags::kUsb;
240 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700241
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700242 auto disk =
243 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
244 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
245 break;
246 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700247 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700248 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700249 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700250 case NetlinkEvent::Action::kChange: {
251 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
252 handleDiskChanged(device);
253 break;
254 }
255 case NetlinkEvent::Action::kRemove: {
256 handleDiskRemoved(device);
257 break;
258 }
259 default: {
260 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
261 break;
262 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700263 }
264}
265
Jeff Sharkey401b2602017-12-14 22:15:20 -0700266void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
267 // For security reasons, if secure keyguard is showing, wait
268 // until the user unlocks the device to actually touch it
Martijn Coenencf5916f2020-01-03 14:36:45 +0100269 // Additionally, wait until user 0 is actually started, since we need
270 // the user to be up before we can mount a FUSE daemon to handle the disk.
271 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700272 if (mSecureKeyguardShowing) {
273 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700274 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700275 mPendingDisks.push_back(disk);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100276 } else if (!userZeroStarted) {
277 LOG(INFO) << "Found disk at " << disk->getEventPath()
278 << " but delaying scan due to user zero not having started";
279 mPendingDisks.push_back(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700280 } else {
281 disk->create();
282 mDisks.push_back(disk);
283 }
284}
285
286void VolumeManager::handleDiskChanged(dev_t device) {
287 for (const auto& disk : mDisks) {
288 if (disk->getDevice() == device) {
289 disk->readMetadata();
290 disk->readPartitions();
291 }
292 }
293
294 // For security reasons, we ignore all pending disks, since
295 // we'll scan them once the device is unlocked
296}
297
298void VolumeManager::handleDiskRemoved(dev_t device) {
299 auto i = mDisks.begin();
300 while (i != mDisks.end()) {
301 if ((*i)->getDevice() == device) {
302 (*i)->destroy();
303 i = mDisks.erase(i);
304 } else {
305 ++i;
306 }
307 }
308 auto j = mPendingDisks.begin();
309 while (j != mPendingDisks.end()) {
310 if ((*j)->getDevice() == device) {
311 j = mPendingDisks.erase(j);
312 } else {
313 ++j;
314 }
315 }
316}
317
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800319 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700320 mDiskSources.push_back(diskSource);
321}
322
323std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
324 for (auto disk : mDisks) {
325 if (disk->getId() == id) {
326 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700327 }
328 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700329 return nullptr;
330}
San Mehatf1b736b2009-10-10 17:22:08 -0700331
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700332std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Zima438b242019-09-25 14:37:38 +0100333 for (const auto& vol : mInternalEmulatedVolumes) {
334 if (vol->getId() == id) {
335 return vol;
336 }
San Mehatf1b736b2009-10-10 17:22:08 -0700337 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700338 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700339 auto vol = disk->findVolume(id);
340 if (vol != nullptr) {
341 return vol;
342 }
343 }
Risan8c9f3322018-10-29 08:52:56 +0900344 for (const auto& vol : mStubVolumes) {
345 if (vol->getId() == id) {
346 return vol;
347 }
348 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600349 for (const auto& vol : mObbVolumes) {
350 if (vol->getId() == id) {
351 return vol;
352 }
353 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700354 return nullptr;
355}
356
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800357void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
358 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700359 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700360 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700361 disk->listVolumes(type, list);
362 }
363}
364
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600365int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700366 std::string normalizedGuid;
367 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
368 LOG(WARNING) << "Invalid GUID " << partGuid;
369 return -1;
370 }
371
Paul Crowleyc6433a22017-10-24 14:54:43 -0700372 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700373 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
374 if (unlink(keyPath.c_str()) != 0) {
375 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700376 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700377 }
Eric Biggersa701c452018-10-23 13:06:55 -0700378 if (fscrypt_is_native()) {
379 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700380 success = false;
381 }
382 }
383 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700384}
385
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700386int VolumeManager::linkPrimary(userid_t userId) {
Abhijeet Kaur01fa0e02019-12-13 10:26:32 +0000387 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
Zima438b242019-09-25 14:37:38 +0100388 std::string source(mPrimary->getPath());
389 if (mPrimary->isEmulated()) {
390 source = StringPrintf("%s/%d", source.c_str(), userId);
391 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
392 }
Zim3623a212019-07-19 16:46:53 +0100393
Zima438b242019-09-25 14:37:38 +0100394 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
395 LOG(DEBUG) << "Linking " << source << " to " << target;
396 Symlink(source, target);
Zim3623a212019-07-19 16:46:53 +0100397 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700398 return 0;
399}
400
Zima438b242019-09-25 14:37:38 +0100401void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
402 // Destroy and remove all unstacked EmulatedVolumes for the user
403 auto i = mInternalEmulatedVolumes.begin();
404 while (i != mInternalEmulatedVolumes.end()) {
405 auto vol = *i;
406 if (vol->getMountUserId() == userId) {
407 vol->destroy();
408 i = mInternalEmulatedVolumes.erase(i);
409 } else {
410 i++;
411 }
412 }
413
414 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
415 std::list<std::string> private_vols;
416 listVolumes(VolumeBase::Type::kPrivate, private_vols);
417 for (const std::string& id : private_vols) {
418 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
419 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
420 if (pvol->getState() == VolumeBase::State::kMounted) {
421 for (const auto& vol : pvol->getVolumes()) {
422 if (vol->getMountUserId() == userId) {
423 vols_to_remove.push_back(vol);
424 }
425 }
426 for (const auto& vol : vols_to_remove) {
427 vol->destroy();
428 pvol->removeVolume(vol);
429 }
430 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
431 }
432}
433
434void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
435 // Create unstacked EmulatedVolumes for the user
436 auto vol = std::shared_ptr<android::vold::VolumeBase>(
437 new android::vold::EmulatedVolume("/data/media", userId));
438 vol->setMountUserId(userId);
439 mInternalEmulatedVolumes.push_back(vol);
440 vol->create();
441
442 // Create stacked EmulatedVolumes for the user on each PrivateVolume
443 std::list<std::string> private_vols;
444 listVolumes(VolumeBase::Type::kPrivate, private_vols);
445 for (const std::string& id : private_vols) {
446 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
447 if (pvol->getState() == VolumeBase::State::kMounted) {
448 auto evol =
449 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
450 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
451 userId));
452 evol->setMountUserId(userId);
453 pvol->addVolume(evol);
454 evol->create();
455 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
456 }
457}
458
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700459int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
Zima438b242019-09-25 14:37:38 +0100460 LOG(INFO) << "onUserAdded: " << userId;
461
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700462 mAddedUsers[userId] = userSerialNumber;
463 return 0;
464}
465
466int VolumeManager::onUserRemoved(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100467 LOG(INFO) << "onUserRemoved: " << userId;
468
Zim2d45d9b2019-11-14 16:19:05 +0000469 onUserStopped(userId);
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700470 mAddedUsers.erase(userId);
471 return 0;
472}
473
Sudheer Shankaebce4cc2019-04-29 10:46:35 -0700474int VolumeManager::onUserStarted(userid_t userId) {
Zima438b242019-09-25 14:37:38 +0100475 LOG(INFO) << "onUserStarted: " << userId;
476
Zim2d45d9b2019-11-14 16:19:05 +0000477 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
478 createEmulatedVolumesForUser(userId);
479 }
480
Abhijeet Kaur01fa0e02019-12-13 10:26:32 +0000481 if (!GetBoolProperty(android::vold::kPropFuse, false)) {
Zima438b242019-09-25 14:37:38 +0100482 // Note that sometimes the system will spin up processes from Zygote
483 // before actually starting the user, so we're okay if Zygote
484 // already created this directory.
485 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
486 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
487
488 if (mPrimary) {
489 linkPrimary(userId);
490 }
491 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700492
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700493 mStartedUsers.insert(userId);
Martijn Coenencf5916f2020-01-03 14:36:45 +0100494
495 createPendingDisksIfNeeded();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700496 return 0;
497}
498
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700499int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700500 LOG(VERBOSE) << "onUserStopped: " << userId;
Zima438b242019-09-25 14:37:38 +0100501
Zim2d45d9b2019-11-14 16:19:05 +0000502 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
Zima438b242019-09-25 14:37:38 +0100503 destroyEmulatedVolumesForUser(userId);
504 }
505
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700506 mStartedUsers.erase(userId);
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700507 return 0;
508}
509
Martijn Coenencf5916f2020-01-03 14:36:45 +0100510void VolumeManager::createPendingDisksIfNeeded() {
511 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
512 if (!mSecureKeyguardShowing && userZeroStarted) {
513 // Now that secure keyguard has been dismissed and user 0 has
514 // started, process any pending disks
Jeff Sharkey401b2602017-12-14 22:15:20 -0700515 for (const auto& disk : mPendingDisks) {
516 disk->create();
517 mDisks.push_back(disk);
518 }
519 mPendingDisks.clear();
520 }
Martijn Coenencf5916f2020-01-03 14:36:45 +0100521}
522
523int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
524 mSecureKeyguardShowing = isShowing;
525 createPendingDisksIfNeeded();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700526 return 0;
527}
528
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700529int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
530 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700531 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700532 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700533 }
534 return 0;
535}
536
Narayan Kamath02efdf52019-11-27 10:53:51 +0000537// This code is executed after a fork so it's very important that the set of
538// methods we call here is strictly limited.
539//
540// TODO: Get rid of this guesswork altogether and instead exec a process
541// immediately after fork to do our bindding for us.
542static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
543 struct dirent* de) {
544 if (setns(nsFd, CLONE_NEWNS) != 0) {
545 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", de->d_name,
546 strerror(errno));
547 return false;
548 }
549
550 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
551 // to also protect against future changes that may cause issues across a
552 // fork.
553 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
554 errno != ENOENT) {
555 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
556 strerror(errno));
557 return false;
558 }
559
560 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
561 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
562 storageSource, de->d_name, strerror(errno));
563 return false;
564 }
565
566 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
567 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
568 "Failed to set MS_SLAVE to /storage for %s :%s", de->d_name,
569 strerror(errno));
570 return false;
571 }
572
573 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
574 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
575 userSource, de->d_name, strerror(errno));
576 return false;
577 }
578
579 return true;
580}
581
Sudheer Shanka817b9112018-12-13 17:40:28 -0800582int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
Abhijeet Kaur01fa0e02019-12-13 10:26:32 +0000583 if (GetBoolProperty(android::vold::kPropFuse, false)) {
Zim3623a212019-07-19 16:46:53 +0100584 // TODO(135341433): Implement fuse specific logic.
585 return 0;
586 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800587 std::string mode;
588 switch (mountMode) {
589 case VoldNativeService::REMOUNT_MODE_NONE:
590 mode = "none";
591 break;
592 case VoldNativeService::REMOUNT_MODE_DEFAULT:
593 mode = "default";
594 break;
595 case VoldNativeService::REMOUNT_MODE_READ:
596 mode = "read";
597 break;
598 case VoldNativeService::REMOUNT_MODE_WRITE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700599 case VoldNativeService::REMOUNT_MODE_LEGACY:
600 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Sudheer Shanka817b9112018-12-13 17:40:28 -0800601 mode = "write";
602 break;
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -0700603 case VoldNativeService::REMOUNT_MODE_FULL:
604 mode = "full";
605 break;
Zim981222f2019-09-09 10:24:44 +0100606 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
607 mode = "pass_through";
608 break;
Sudheer Shanka817b9112018-12-13 17:40:28 -0800609 default:
610 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
611 return -1;
612 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700613 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
614
615 DIR* dir;
616 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600617 std::string rootName;
618 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700619 int pidFd;
620 int nsFd;
621 struct stat sb;
622 pid_t child;
Narayan Kamath02efdf52019-11-27 10:53:51 +0000623 std::string userSource;
624 std::string storageSource;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700625
Jiyong Park8d21c922019-01-04 13:35:25 +0900626 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
627
Jeff Sharkey66270a22015-06-24 11:49:24 -0700628 if (!(dir = opendir("/proc"))) {
629 PLOG(ERROR) << "Failed to opendir";
630 return -1;
631 }
632
633 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600634 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
635 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700636 closedir(dir);
637 return -1;
638 }
639
640 // Poke through all running PIDs look for apps running as UID
641 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700642 pid_t pid;
643 if (de->d_type != DT_DIR) continue;
644 if (!android::base::ParseInt(de->d_name, &pid)) continue;
645
Jeff Sharkey66270a22015-06-24 11:49:24 -0700646 pidFd = -1;
647 nsFd = -1;
648
649 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
650 if (pidFd < 0) {
651 goto next;
652 }
653 if (fstat(pidFd, &sb) != 0) {
654 PLOG(WARNING) << "Failed to stat " << de->d_name;
655 goto next;
656 }
657 if (sb.st_uid != uid) {
658 goto next;
659 }
660
661 // Matches so far, but refuse to touch if in root namespace
662 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600663 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700664 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
665 goto next;
666 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600667 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700668 LOG(WARNING) << "Skipping due to root namespace";
669 goto next;
670 }
671
Jiyong Park8d21c922019-01-04 13:35:25 +0900672 if (apexUpdatable) {
673 std::string exeName;
674 // When ro.apex.bionic_updatable is set to true,
675 // some early native processes have mount namespaces that are different
676 // from that of the init. Therefore, above check can't filter them out.
677 // Since the propagation type of / is 'shared', unmounting /storage
678 // for the early native processes affects other processes including
679 // init. Filter out such processes by skipping if a process is a
680 // non-Java process whose UID is < AID_APP_START. (The UID condition
681 // is required to not filter out child processes spawned by apps.)
682 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
683 PLOG(WARNING) << "Failed to read exe name for " << de->d_name;
684 goto next;
685 }
686 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
687 LOG(WARNING) << "Skipping due to native system process";
688 goto next;
689 }
690 }
691
Jeff Sharkey66270a22015-06-24 11:49:24 -0700692 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -0700693 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
694 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700695 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700696 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700697 goto next;
698 }
699
Narayan Kamath02efdf52019-11-27 10:53:51 +0000700 if (mode == "default") {
701 storageSource = "/mnt/runtime/default";
702 } else if (mode == "read") {
703 storageSource = "/mnt/runtime/read";
704 } else if (mode == "write") {
705 storageSource = "/mnt/runtime/write";
706 } else if (mode == "full") {
707 storageSource = "/mnt/runtime/full";
708 } else {
709 // Sane default of no storage visible. No need to fork a child
710 // to remount uid.
711 goto next;
712 }
713
714 // Mount user-specific symlink helper into place
715 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
Jeff Sharkey66270a22015-06-24 11:49:24 -0700716 if (!(child = fork())) {
Narayan Kamath02efdf52019-11-27 10:53:51 +0000717 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, de)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700718 _exit(0);
Narayan Kamath02efdf52019-11-27 10:53:51 +0000719 } else {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700720 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700721 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700722 }
723
724 if (child == -1) {
725 PLOG(ERROR) << "Failed to fork";
726 goto next;
727 } else {
728 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
729 }
730
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700731 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700732 close(nsFd);
733 close(pidFd);
734 }
735 closedir(dir);
736 return 0;
737}
738
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700739int VolumeManager::reset() {
740 // Tear down all existing disks/volumes and start from a blank slate so
741 // newly connected framework hears all events.
Zima438b242019-09-25 14:37:38 +0100742 for (const auto& vol : mInternalEmulatedVolumes) {
743 vol->destroy();
Gao Xiangd263da82017-08-14 11:32:13 +0800744 }
Zima438b242019-09-25 14:37:38 +0100745 mInternalEmulatedVolumes.clear();
Zima438b242019-09-25 14:37:38 +0100746
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700747 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700748 disk->destroy();
749 disk->create();
750 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600751 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700752 mAddedUsers.clear();
Sudheer Shanka023b5392019-02-06 12:39:19 -0800753 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700754 return 0;
755}
756
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700757// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700758int VolumeManager::shutdown() {
Zima438b242019-09-25 14:37:38 +0100759 if (mInternalEmulatedVolumes.empty()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700760 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700761 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700762 android::vold::sSleepOnUnmount = false;
Zima438b242019-09-25 14:37:38 +0100763 for (const auto& vol : mInternalEmulatedVolumes) {
764 vol->destroy();
765 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700766 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700767 disk->destroy();
768 }
Zima438b242019-09-25 14:37:38 +0100769
770 mInternalEmulatedVolumes.clear();
Risan8c9f3322018-10-29 08:52:56 +0900771 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700772 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700773 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700774 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700775 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700776}
777
Jeff Sharkey9c484982015-03-31 10:35:33 -0700778int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700779 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600780 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700781
Jeff Sharkey9c484982015-03-31 10:35:33 -0700782 // First, try gracefully unmounting all known devices
Zima438b242019-09-25 14:37:38 +0100783 for (const auto& vol : mInternalEmulatedVolumes) {
784 vol->unmount();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700785 }
Risan8c9f3322018-10-29 08:52:56 +0900786 for (const auto& stub : mStubVolumes) {
787 stub->unmount();
788 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700789 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700790 disk->unmountAll();
791 }
792
793 // Worst case we might have some stale mounts lurking around, so
794 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +0800795 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -0700796 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600797 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700798 return -errno;
799 }
800
801 // Some volumes can be stacked on each other, so force unmount in
802 // reverse order to give us the best chance of success.
803 std::list<std::string> toUnmount;
804 mntent* mentry;
805 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600806 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700807 if ((StartsWith(test, "/mnt/") &&
808#ifdef __ANDROID_DEBUGGABLE__
809 !StartsWith(test, "/mnt/scratch") &&
810#endif
Martijn Coenenb0e977a2020-01-11 19:24:26 +0100811 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
812 !StartsWith(test, "/mnt/installer")) ||
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700813 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600814 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700815 }
816 }
817 endmntent(fp);
818
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700819 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600820 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700821 android::vold::ForceUnmount(path);
822 }
823
824 return 0;
825}
826
Martijn Coenen62a4b272020-01-31 15:23:09 +0100827static gid_t getAppDirGid(const std::string& appDir) {
828 // Create app-specific dirs with the correct UID/GID
829 gid_t gid = AID_MEDIA_RW;
830 if (!IsFilesystemSupported("sdcardfs")) {
831 if (appDir == android::vold::kAppDataDir) {
832 gid = AID_EXT_DATA_RW;
833 } else if (appDir == android::vold::kAppObbDir) {
834 gid = AID_EXT_OBB_RW;
835 } else if (appDir == android::vold::kAppMediaDir) {
836 gid = AID_MEDIA_RW;
837 } else {
838 gid = AID_MEDIA_RW;
839 }
840 }
841
842 return gid;
843}
844
845static bool isValidAppDirRoot(const std::string& appDirRoot) {
846 return appDirRoot == android::vold::kAppDataDir || appDirRoot == android::vold::kAppMediaDir ||
847 appDirRoot == android::vold::kAppObbDir;
848}
849
Martijn Coenen13ff6682019-12-24 12:57:16 +0100850int VolumeManager::setupAppDir(const std::string& path, const std::string& appDirRoot,
851 int32_t appUid) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700852 // Only offer to create directories for paths managed by vold
Martijn Coenen13ff6682019-12-24 12:57:16 +0100853 if (!StartsWith(path, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600854 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700855 return -EINVAL;
856 }
Martijn Coenen13ff6682019-12-24 12:57:16 +0100857
Martijn Coenen0a7e9922020-01-24 16:17:32 +0100858 // Find the volume it belongs to
859 auto filter_fn = [&](const VolumeBase& vol) {
860 if (vol.getState() != VolumeBase::State::kMounted) {
861 // The volume must be mounted
862 return false;
863 }
864 if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
865 // and visible
866 return false;
867 }
868 if (vol.getInternalPath().empty()) {
869 return false;
870 }
871 if (vol.getMountUserId() != USER_UNKNOWN &&
872 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
873 // The app dir must be created on a volume with the same user-id
874 return false;
875 }
876 if (!path.empty() && StartsWith(path, vol.getPath())) {
877 return true;
878 }
879
880 return false;
881 };
882 auto volume = findVolumeWithFilter(filter_fn);
883 if (volume == nullptr) {
884 LOG(ERROR) << "Failed to find mounted volume for " << path;
885 return -EINVAL;
886 }
Zimc59d7742020-01-06 21:48:16 +0000887 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
888 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
889 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
890 // on /storage/emulated/10 means /mnt/user/0/emulated/10
Martijn Coenen0a7e9922020-01-24 16:17:32 +0100891 const std::string lowerPath =
892 volume->getInternalPath() + path.substr(volume->getPath().length());
893 const std::string lowerAppDirRoot =
894 volume->getInternalPath() + appDirRoot.substr(volume->getPath().length());
Zimc59d7742020-01-06 21:48:16 +0000895
Martijn Coenen62a4b272020-01-31 15:23:09 +0100896 // Do some sanity checking on the app dir (relative from root)
897 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
898
899 // eg, if lowerAppDirRoot = /data/media/0/Android/data, this is /Android/data
900 const std::string relativeAppRoot = lowerAppDirRoot.substr(volumeRoot.length());
901 if (!isValidAppDirRoot(relativeAppRoot)) {
902 LOG(ERROR) << path << " is not a valid application directory.";
903 return -EINVAL;
904 }
905
906 // Make sure the Android/ directories exist and are setup correctly
907 int ret = PrepareAndroidDirs(volumeRoot);
Martijn Coenen13ff6682019-12-24 12:57:16 +0100908 if (ret != 0) {
Martijn Coenen62a4b272020-01-31 15:23:09 +0100909 LOG(ERROR) << "Failed to prepare Android/ directories.";
Martijn Coenen13ff6682019-12-24 12:57:16 +0100910 return ret;
911 }
Martijn Coenen62a4b272020-01-31 15:23:09 +0100912
913 gid_t gid = getAppDirGid(relativeAppRoot);
914 return PrepareAppDirsFromRoot(lowerPath, lowerAppDirRoot, 0770, appUid, gid);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700915}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600916
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600917int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700918 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600919 int id = mNextObbId++;
920
921 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700922 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600923 vol->create();
924
925 mObbVolumes.push_back(vol);
926 *outVolId = vol->getId();
927 return android::OK;
928}
929
930int VolumeManager::destroyObb(const std::string& volId) {
931 auto i = mObbVolumes.begin();
932 while (i != mObbVolumes.end()) {
933 if ((*i)->getId() == volId) {
934 (*i)->destroy();
935 i = mObbVolumes.erase(i);
936 } else {
937 ++i;
938 }
939 }
940 return android::OK;
941}
942
Risan8c9f3322018-10-29 08:52:56 +0900943int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
944 const std::string& fsType, const std::string& fsUuid,
945 const std::string& fsLabel, std::string* outVolId) {
946 int id = mNextStubVolumeId++;
947 auto vol = std::shared_ptr<android::vold::VolumeBase>(
948 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
949 vol->create();
950
951 mStubVolumes.push_back(vol);
952 *outVolId = vol->getId();
953 return android::OK;
954}
955
956int VolumeManager::destroyStubVolume(const std::string& volId) {
957 auto i = mStubVolumes.begin();
958 while (i != mStubVolumes.end()) {
959 if ((*i)->getId() == volId) {
960 (*i)->destroy();
961 i = mStubVolumes.erase(i);
962 } else {
963 ++i;
964 }
965 }
966 return android::OK;
967}
968
Risan8f6198d2018-10-26 20:56:45 -0600969int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -0600970 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600971}
972
Risan8f6198d2018-10-26 20:56:45 -0600973int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -0600974 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -0600975}
976
977int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -0600978 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600979}