blob: 0068cb6763f799a84fcad7c033a7c9e44d0f3a2b [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
Elliott Hughes7e128fb2015-12-04 15:50:53 -080037#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070038#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060039#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080040#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070041#include <android-base/strings.h>
42
Jeff Sharkey71ebe152013-09-17 17:24:38 -070043#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060044#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070045
Robert Craigb9e3ba52014-02-04 10:53:00 -050046#include <selinux/android.h>
47
San Mehatfd7f5872009-10-12 11:32:47 -070048#include <sysutils/NetlinkEvent.h>
49
Kenny Root344ca102012-04-03 17:23:01 -070050#include <private/android_filesystem_config.h>
51
Eric Biggersa701c452018-10-23 13:06:55 -070052#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070053
Risanac02a482018-10-31 21:59:47 -060054#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070055#include "Devmapper.h"
Eric Biggersa701c452018-10-23 13:06:55 -070056#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080057#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070058#include "NetlinkManager.h"
59#include "Process.h"
60#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070061#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070062#include "VoldUtil.h"
63#include "VolumeManager.h"
64#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070065#include "fs/Ext4.h"
66#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070067#include "model/EmulatedVolume.h"
68#include "model/ObbVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090069#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080070
Sudheer Shanka53947a32018-08-01 10:24:13 -070071using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070072using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070073using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070074using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060075using android::base::unique_fd;
Sudheer Shanka03992e32018-12-12 12:43:38 -080076using android::vold::VoldNativeService;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070077
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060078static const char* kPathUserMount = "/mnt/user";
79static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
80
Sudheer Shanka53947a32018-08-01 10:24:13 -070081static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060082static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
83
Sudheer Shanka53947a32018-08-01 10:24:13 -070084static const std::string kEmptyString("");
85
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060086/* 512MiB is large enough for testing purposes */
87static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070088
Jeff Sharkey36801cc2015-03-13 16:09:20 -070089static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080090static const unsigned int kMajorBlockExperimentalMin = 240;
91static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070092
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070093VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070094
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070095VolumeManager* VolumeManager::Instance() {
96 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070097 return sInstance;
98}
99
100VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800101 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600102 mNextObbId = 0;
Risan8c9f3322018-10-29 08:52:56 +0900103 mNextStubVolumeId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700104 // For security reasons, assume that a secure keyguard is
105 // showing until we hear otherwise
106 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700107}
108
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700109VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800110
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600111int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600112 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700113 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600114 if (access(kPathVirtualDisk, F_OK) != 0) {
115 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
116 }
117
118 if (mVirtualDisk == nullptr) {
119 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
120 LOG(ERROR) << "Failed to create virtual disk";
121 return -1;
122 }
123
124 struct stat buf;
125 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
126 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
127 return -1;
128 }
129
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700130 auto disk = new android::vold::Disk(
131 "virtual", buf.st_rdev, "virtual",
132 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600133 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700134 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600135 }
136 } else {
137 if (mVirtualDisk != nullptr) {
138 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700139 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600140
141 Loop::destroyByDevice(mVirtualDiskPath.c_str());
142 mVirtualDisk = nullptr;
143 }
144
145 if (access(kPathVirtualDisk, F_OK) == 0) {
146 unlink(kPathVirtualDisk);
147 }
148 }
149 return 0;
150}
151
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700152int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800153 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700154 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800155}
156
San Mehatf1b736b2009-10-10 17:22:08 -0700157int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600158 ATRACE_NAME("VolumeManager::start");
159
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700160 // Always start from a clean slate by unmounting everything in
161 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700162 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700163
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600164 Devmapper::destroyAll();
165 Loop::destroyAll();
166
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700167 // Assume that we always have an emulated volume on internal
168 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700169 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700170 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700171 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700172 mInternalEmulated->create();
173
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600174 // Consider creating a virtual disk
175 updateVirtualDisk();
176
San Mehatf1b736b2009-10-10 17:22:08 -0700177 return 0;
178}
179
180int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700181 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700182 mInternalEmulated->destroy();
183 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700184 return 0;
185}
186
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700187void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700188 std::lock_guard<std::mutex> lock(mLock);
189
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700190 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700191 LOG(DEBUG) << "----------------";
192 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700193 evt->dump();
194 }
San Mehatf1b736b2009-10-10 17:22:08 -0700195
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700196 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
197 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700198
199 if (devType != "disk") return;
200
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600201 int major = std::stoi(evt->findParam("MAJOR"));
202 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700203 dev_t device = makedev(major, minor);
204
205 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700206 case NetlinkEvent::Action::kAdd: {
207 for (const auto& source : mDiskSources) {
208 if (source->matches(eventPath)) {
209 // For now, assume that MMC and virtio-blk (the latter is
210 // emulator-specific; see Disk.cpp for details) devices are SD,
211 // and that everything else is USB
212 int flags = source->getFlags();
213 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
214 major >= (int)kMajorBlockExperimentalMin &&
215 major <= (int)kMajorBlockExperimentalMax)) {
216 flags |= android::vold::Disk::Flags::kSd;
217 } else {
218 flags |= android::vold::Disk::Flags::kUsb;
219 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700220
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700221 auto disk =
222 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
223 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
224 break;
225 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700226 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700227 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700228 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700229 case NetlinkEvent::Action::kChange: {
230 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
231 handleDiskChanged(device);
232 break;
233 }
234 case NetlinkEvent::Action::kRemove: {
235 handleDiskRemoved(device);
236 break;
237 }
238 default: {
239 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
240 break;
241 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700242 }
243}
244
Jeff Sharkey401b2602017-12-14 22:15:20 -0700245void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
246 // For security reasons, if secure keyguard is showing, wait
247 // until the user unlocks the device to actually touch it
248 if (mSecureKeyguardShowing) {
249 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700250 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700251 mPendingDisks.push_back(disk);
252 } else {
253 disk->create();
254 mDisks.push_back(disk);
255 }
256}
257
258void VolumeManager::handleDiskChanged(dev_t device) {
259 for (const auto& disk : mDisks) {
260 if (disk->getDevice() == device) {
261 disk->readMetadata();
262 disk->readPartitions();
263 }
264 }
265
266 // For security reasons, we ignore all pending disks, since
267 // we'll scan them once the device is unlocked
268}
269
270void VolumeManager::handleDiskRemoved(dev_t device) {
271 auto i = mDisks.begin();
272 while (i != mDisks.end()) {
273 if ((*i)->getDevice() == device) {
274 (*i)->destroy();
275 i = mDisks.erase(i);
276 } else {
277 ++i;
278 }
279 }
280 auto j = mPendingDisks.begin();
281 while (j != mPendingDisks.end()) {
282 if ((*j)->getDevice() == device) {
283 j = mPendingDisks.erase(j);
284 } else {
285 ++j;
286 }
287 }
288}
289
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700290void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800291 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700292 mDiskSources.push_back(diskSource);
293}
294
295std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
296 for (auto disk : mDisks) {
297 if (disk->getId() == id) {
298 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700299 }
300 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700301 return nullptr;
302}
San Mehatf1b736b2009-10-10 17:22:08 -0700303
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700304std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800305 // Vold could receive "mount" after "shutdown" command in the extreme case.
306 // If this happens, mInternalEmulated will equal nullptr and
307 // we need to deal with it in order to avoid null pointer crash.
308 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700309 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700310 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700311 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700312 auto vol = disk->findVolume(id);
313 if (vol != nullptr) {
314 return vol;
315 }
316 }
Risan8c9f3322018-10-29 08:52:56 +0900317 for (const auto& vol : mStubVolumes) {
318 if (vol->getId() == id) {
319 return vol;
320 }
321 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600322 for (const auto& vol : mObbVolumes) {
323 if (vol->getId() == id) {
324 return vol;
325 }
326 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700327 return nullptr;
328}
329
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800330void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
331 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700332 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700333 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700334 disk->listVolumes(type, list);
335 }
336}
337
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600338int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700339 std::string normalizedGuid;
340 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
341 LOG(WARNING) << "Invalid GUID " << partGuid;
342 return -1;
343 }
344
Paul Crowleyc6433a22017-10-24 14:54:43 -0700345 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700346 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
347 if (unlink(keyPath.c_str()) != 0) {
348 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700349 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700350 }
Eric Biggersa701c452018-10-23 13:06:55 -0700351 if (fscrypt_is_native()) {
352 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700353 success = false;
354 }
355 }
356 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700357}
358
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700359int VolumeManager::linkPrimary(userid_t userId) {
360 std::string source(mPrimary->getPath());
361 if (mPrimary->isEmulated()) {
362 source = StringPrintf("%s/%d", source.c_str(), userId);
363 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
364 }
365
366 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
367 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
368 if (errno != ENOENT) {
369 PLOG(WARNING) << "Failed to unlink " << target;
370 }
371 }
372 LOG(DEBUG) << "Linking " << source << " to " << target;
373 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
374 PLOG(WARNING) << "Failed to link";
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700375 return -errno;
376 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700377 return 0;
378}
379
380int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
381 const std::string& mntTargetRoot,
382 const std::string& packageName, const char* dirName) {
383 std::string mntSourceDir =
384 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
385 std::string mntTargetDir =
386 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
387 if (umount2(mntTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL && errno != ENOENT) {
388 PLOG(ERROR) << "Failed to unmount " << mntTargetDir;
389 return -1;
390 }
391 if (TEMP_FAILURE_RETRY(mount(mntSourceDir.c_str(), mntTargetDir.c_str(), nullptr,
392 MS_BIND | MS_REC, nullptr)) == -1) {
393 PLOG(ERROR) << "Failed to mount " << mntSourceDir << " to " << mntTargetDir;
394 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700395 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700396 if (TEMP_FAILURE_RETRY(
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700397 mount(nullptr, mntTargetDir.c_str(), nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
398 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTargetDir;
399 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700400 }
401 return 0;
402}
403
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700404int VolumeManager::mountPkgSpecificDirsForRunningProcs(
405 userid_t userId, const std::vector<std::string>& packageNames,
Sudheer Shanka817b9112018-12-13 17:40:28 -0800406 const std::vector<std::string>& visibleVolLabels, int remountMode) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700407 // TODO: New processes could be started while traversing over the existing
408 // processes which would end up not having the necessary bind mounts. This
409 // issue needs to be fixed, may be by doing multiple passes here?
410 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
411 if (!dirp) {
412 PLOG(ERROR) << "Failed to opendir /proc";
413 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700414 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700415
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700416 std::string rootName;
417 // Figure out root namespace to compare against below
418 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
419 PLOG(ERROR) << "Failed to read root namespace";
420 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700421 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700422
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700423 struct stat fullWriteSb;
424 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &fullWriteSb)) == -1) {
425 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
426 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700427 }
428
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700429 std::unordered_set<appid_t> validAppIds;
430 for (auto& package : packageNames) {
431 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700432 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700433 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700434
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700435 struct dirent* de;
436 // Poke through all running PIDs look for apps running in userId
437 while ((de = readdir(dirp.get()))) {
438 pid_t pid;
439 if (de->d_type != DT_DIR) continue;
440 if (!android::base::ParseInt(de->d_name, &pid)) continue;
441
442 const unique_fd pidFd(
443 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
444 if (pidFd.get() < 0) {
445 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700446 continue;
447 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700448 struct stat sb;
449 if (fstat(pidFd.get(), &sb) != 0) {
450 PLOG(WARNING) << "Failed to stat " << de->d_name;
451 continue;
452 }
453 if (multiuser_get_user_id(sb.st_uid) != userId) {
454 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700455 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700456
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700457 // Matches so far, but refuse to touch if in root namespace
458 LOG(VERBOSE) << "Found matching PID " << de->d_name;
459 std::string pidName;
460 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
461 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
462 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700463 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700464 if (rootName == pidName) {
465 LOG(WARNING) << "Skipping due to root namespace";
466 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700467 }
468
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700469 // Only update the mount points of processes running with one of validAppIds.
470 // This should skip any isolated uids.
471 appid_t appId = multiuser_get_app_id(sb.st_uid);
472 if (validAppIds.find(appId) == validAppIds.end()) {
473 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700474 }
475
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700476 std::vector<std::string> packagesForUid;
477 for (auto& package : userPackages) {
478 if (mAppIds[package] == appId) {
479 packagesForUid.push_back(package);
480 }
481 }
482 if (packagesForUid.empty()) {
483 continue;
484 }
485 const std::string& sandboxId = mSandboxIds[appId];
486
487 // We purposefully leave the namespace open across the fork
488 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
489 if (nsFd.get() < 0) {
490 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
491 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700492 }
493
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700494 pid_t child;
495 if (!(child = fork())) {
496 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
497 PLOG(ERROR) << "Failed to setns for " << de->d_name;
498 _exit(1);
499 }
500
Sudheer Shanka817b9112018-12-13 17:40:28 -0800501 int mountMode;
502 if (remountMode == -1) {
503 mountMode = getMountModeForRunningProc(packagesForUid, userId, fullWriteSb);
504 if (mountMode == -1) {
505 _exit(1);
506 }
507 } else {
508 mountMode = remountMode;
509 std::string obbMountFile = StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId,
510 packagesForUid[0].c_str());
511 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
512 if (access(obbMountFile.c_str(), F_OK) != 0) {
513 const unique_fd fd(
514 TEMP_FAILURE_RETRY(open(obbMountFile.c_str(), O_RDWR | O_CREAT, 0660)));
515 }
516 } else {
517 if (access(obbMountFile.c_str(), F_OK) == 0) {
518 remove(obbMountFile.c_str());
519 }
520 }
521 }
522 if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
523 mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
524 // These mount modes are not going to change dynamically, so don't bother
525 // unmounting/remounting dirs.
526 _exit(0);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700527 }
528
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700529 for (auto& volumeLabel : visibleVolLabels) {
530 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
531 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
532 if (volumeLabel == "emulated") {
533 StringAppendF(&mntSource, "/%d", userId);
534 StringAppendF(&mntTarget, "/%d", userId);
535 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800536 std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
537 std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
538 if (umount2(obbTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
539 errno != ENOENT) {
540 PLOG(ERROR) << "Failed to unmount " << obbTargetDir;
541 continue;
542 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700543 for (auto& package : packagesForUid) {
544 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
545 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
Sudheer Shanka03992e32018-12-12 12:43:38 -0800546 if (mountMode != VoldNativeService::REMOUNT_MODE_INSTALLER) {
547 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
548 }
549 }
550 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800551 if (TEMP_FAILURE_RETRY(mount(obbSourceDir.c_str(), obbTargetDir.c_str(),
552 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
553 PLOG(ERROR) << "Failed to mount " << obbSourceDir << " to " << obbTargetDir;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800554 continue;
555 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800556 if (TEMP_FAILURE_RETRY(mount(nullptr, obbTargetDir.c_str(), nullptr,
Sudheer Shanka03992e32018-12-12 12:43:38 -0800557 MS_REC | MS_SLAVE, nullptr)) == -1) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800558 PLOG(ERROR) << "Failed to set MS_SLAVE at " << obbTargetDir.c_str();
Sudheer Shanka03992e32018-12-12 12:43:38 -0800559 continue;
560 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700561 }
562 }
563 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700564 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700565
566 if (child == -1) {
567 PLOG(ERROR) << "Failed to fork";
568 } else {
569 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700570 }
571 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700572 return 0;
573}
574
Sudheer Shanka03992e32018-12-12 12:43:38 -0800575int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
576 userid_t userId, struct stat& mntWriteStat) {
577 struct stat storageSb;
578 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
579 PLOG(ERROR) << "Failed to stat /storage";
580 return -1;
581 }
582
583 // Some packages have access to full external storage, identify processes belonging
584 // to those packages by comparing inode no.s of /mnt/runtime/write and /storage
585 if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
586 return VoldNativeService::REMOUNT_MODE_FULL;
587 }
588
589 std::string obbMountFile =
590 StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId, packagesForUid[0].c_str());
591 if (access(obbMountFile.c_str(), F_OK) == 0) {
592 return VoldNativeService::REMOUNT_MODE_INSTALLER;
593 }
594
595 // Some packages don't have access to external storage and processes belonging to
596 // those packages don't have anything mounted at /storage. So, identify those
597 // processes by comparing inode no.s of /mnt/user/%d/package/%s
598 // and /storage
599 for (auto& package : packagesForUid) {
600 std::string sandbox = StringPrintf("/mnt/user/%d/package/%s", userId, package.c_str());
601 struct stat sandboxStat;
602 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
603 PLOG(ERROR) << "Failed to stat " << sandbox;
604 return -1;
605 }
606 if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
607 return VoldNativeService::REMOUNT_MODE_WRITE;
608 }
609 }
610 return VoldNativeService::REMOUNT_MODE_NONE;
611}
612
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700613int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
614 const std::vector<std::string>& visibleVolLabels) {
615 if (visibleVolLabels.empty()) {
616 return 0;
617 }
618 for (auto& volumeLabel : visibleVolLabels) {
619 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
620 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
621 if (isVolPrimaryEmulated) {
622 StringAppendF(&volumeRoot, "/%d", userId);
623 if (fs_prepare_dir(volumeRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
624 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeRoot;
625 return -errno;
626 }
627 }
628
629 std::string sandboxRoot =
630 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
631 if (sandboxRoot.empty()) {
632 return -errno;
633 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700634
635 if (!createPkgSpecificDirRoots(volumeRoot)) {
636 return -errno;
637 }
638
639 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
640 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
641 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
642 return -errno;
643 }
644 mntTargetRoot.append("/package");
645 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
646 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
647 return -errno;
648 }
649
650 for (auto& packageName : packageNames) {
651 const auto& it = mAppIds.find(packageName);
652 if (it == mAppIds.end()) {
653 PLOG(ERROR) << "appId is not available for " << packageName;
654 continue;
655 }
656 appid_t appId = it->second;
657 std::string sandboxId = mSandboxIds[appId];
658 uid_t uid = multiuser_get_uid(userId, appId);
659
660 // [1] Create /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
661 // [2] Create /mnt/user/0/package/<packageName>/emulated/0
662 // Mount [1] at [2]
663 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
664 if (pkgSandboxSourceDir.empty()) {
665 return -errno;
666 }
667 std::string pkgSandboxTargetDir = prepareSandboxTarget(
668 packageName, uid, volumeLabel, mntTargetRoot, isVolPrimaryEmulated);
669 if (pkgSandboxTargetDir.empty()) {
670 return -errno;
671 }
672 if (umount2(pkgSandboxTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
673 errno != ENOENT) {
674 PLOG(ERROR) << "Failed to unmount " << pkgSandboxTargetDir;
675 return -errno;
676 }
677 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
678 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
679 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
680 << pkgSandboxTargetDir;
681 return -errno;
682 }
683 if (TEMP_FAILURE_RETRY(mount(nullptr, pkgSandboxTargetDir.c_str(), nullptr,
684 MS_SLAVE | MS_REC, nullptr)) == -1) {
685 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
686 << pkgSandboxTargetDir;
687 return -errno;
688 }
689
690 // Create Android/{data,media,obb}/<packageName> segments at
691 // [1] /mnt/runtime/write/emulated/0/ and
692 // [2] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>/emulated/0/
693 if (!createPkgSpecificDirs(packageName, uid, volumeRoot, pkgSandboxSourceDir)) {
694 return -errno;
695 }
696
697 if (volumeLabel == mPrimary->getLabel()) {
698 // Create [1] /mnt/user/0/package/<packageName>/self/
699 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
700 // Mount [2] at [1]
701 std::string pkgPrimaryTargetDir =
702 StringPrintf("%s/%s/self", mntTargetRoot.c_str(), packageName.c_str());
703 if (fs_prepare_dir(pkgPrimaryTargetDir.c_str(), 0755, uid, uid) != 0) {
704 PLOG(ERROR) << "Failed to fs_prepare_dir on " << pkgPrimaryTargetDir;
705 return -errno;
706 }
707 StringAppendF(&pkgPrimaryTargetDir, "/primary");
708 std::string primarySource(mPrimary->getPath());
709 if (isVolPrimaryEmulated) {
710 StringAppendF(&primarySource, "/%d", userId);
711 }
712 if (TEMP_FAILURE_RETRY(unlink(pkgPrimaryTargetDir.c_str()))) {
713 if (errno != ENOENT) {
714 PLOG(ERROR) << "Failed to unlink " << pkgPrimaryTargetDir;
715 }
716 }
717 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), pkgPrimaryTargetDir.c_str()))) {
718 PLOG(ERROR) << "Failed to link " << primarySource << " at "
719 << pkgPrimaryTargetDir;
720 return -errno;
721 }
722 }
723 }
724 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800725 mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700726 return 0;
727}
728
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700729std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
730 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700731 std::string path(pathPrefix);
732 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
733 for (size_t i = 0; i < subDirList.size(); ++i) {
734 std::string subDir = subDirList[i];
735 if (subDir.empty()) {
736 continue;
737 }
738 StringAppendF(&path, "/%s", subDir.c_str());
739 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
740 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
741 return kEmptyString;
742 }
743 }
744 return path;
745}
746
747std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700748 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700749 std::string sandboxSourceDir(sandboxRootDir);
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700750 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700751 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
752 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
753 return kEmptyString;
754 }
755 return sandboxSourceDir;
756}
757
758std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700759 const std::string& volumeLabel,
760 const std::string& mntTargetRootDir,
761 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700762 std::string segment;
763 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700764 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
765 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700766 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700767 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700768 }
769 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
770}
771
772std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700773 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700774 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
775 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
776 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
777 return kEmptyString;
778 }
779 return dataSourceDir;
780}
781
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700782bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
783 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
784 if (fs_prepare_dir(volumeAndroidRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
785 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeAndroidRoot;
786 return false;
787 }
788 std::array<std::string, 3> dirs = {"data", "media", "obb"};
789 for (auto& dir : dirs) {
790 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
791 if (fs_prepare_dir(path.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
792 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
793 return false;
794 }
795 }
796 return true;
797}
798
799bool VolumeManager::createPkgSpecificDirs(const std::string& packageName, uid_t uid,
800 const std::string& volumeRoot,
801 const std::string& sandboxDirRoot) {
802 std::array<std::string, 3> dirs = {"data", "media", "obb"};
803 for (auto& dir : dirs) {
804 std::string sourceDir = StringPrintf("%s/Android/%s", volumeRoot.c_str(), dir.c_str());
805 if (prepareSubDirs(sourceDir, packageName, 0755, uid, uid).empty()) {
806 return false;
807 }
808 std::string sandboxSegment =
809 StringPrintf("Android/%s/%s/", dir.c_str(), packageName.c_str());
810 if (prepareSubDirs(sandboxDirRoot, sandboxSegment, 0755, uid, uid).empty()) {
811 return false;
812 }
813 }
814 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700815}
816
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700817int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
818 mAddedUsers[userId] = userSerialNumber;
819 return 0;
820}
821
822int VolumeManager::onUserRemoved(userid_t userId) {
823 mAddedUsers.erase(userId);
824 return 0;
825}
826
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700827int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
828 const std::vector<int>& appIds,
829 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700830 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700831 // Note that sometimes the system will spin up processes from Zygote
832 // before actually starting the user, so we're okay if Zygote
833 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600834 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700835 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
836
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700837 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700838 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700839 for (size_t i = 0; i < packageNames.size(); ++i) {
840 mAppIds[packageNames[i]] = appIds[i];
841 mSandboxIds[appIds[i]] = sandboxIds[i];
842 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700843 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700844 linkPrimary(userId);
845 }
846 if (GetBoolProperty(kIsolatedStorage, false)) {
847 std::vector<std::string> visibleVolLabels;
848 for (auto& volId : mVisibleVolumeIds) {
849 auto vol = findVolume(volId);
850 userid_t mountUserId = vol->getMountUserId();
851 if (mountUserId == userId || vol->isEmulated()) {
852 visibleVolLabels.push_back(vol->getLabel());
853 }
854 }
855 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
856 return -errno;
857 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700858 }
859 return 0;
860}
861
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700862int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700863 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700864 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700865
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700866 if (GetBoolProperty(kIsolatedStorage, false)) {
867 mUserPackages.erase(userId);
868 std::string mntTargetDir = StringPrintf("/mnt/user/%d", userId);
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800869 if (android::vold::UnmountTreeWithPrefix(mntTargetDir) < 0) {
870 PLOG(ERROR) << "UnmountTreeWithPrefix on " << mntTargetDir << " failed";
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700871 return -errno;
872 }
873 if (android::vold::DeleteDirContentsAndDir(mntTargetDir) < 0) {
874 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << mntTargetDir;
875 return -errno;
876 }
877 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << mntTargetDir;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700878 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700879 return 0;
880}
881
Sudheer Shankad484aa92018-07-31 10:07:34 -0700882int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700883 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700884 for (size_t i = 0; i < packageNames.size(); ++i) {
885 mAppIds[packageNames[i]] = appIds[i];
886 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700887 return 0;
888}
889
890int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700891 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700892 for (size_t i = 0; i < appIds.size(); ++i) {
893 mSandboxIds[appIds[i]] = sandboxIds[i];
894 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700895 return 0;
896}
897
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700898int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
899 const std::string& sandboxId, userid_t userId) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700900 if (!GetBoolProperty(kIsolatedStorage, false)) {
901 return 0;
902 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
903 // User not started, no need to do anything now. Required bind mounts for the package will
904 // be created when the user starts.
905 return 0;
906 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700907 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700908 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700909 mUserPackages[userId].push_back(packageName);
910 mAppIds[packageName] = appId;
911 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700912
913 std::vector<std::string> visibleVolLabels;
914 for (auto& volId : mVisibleVolumeIds) {
915 auto vol = findVolume(volId);
916 userid_t mountUserId = vol->getMountUserId();
917 if (mountUserId == userId || vol->isEmulated()) {
918 visibleVolLabels.push_back(vol->getLabel());
919 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700920 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700921 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700922}
923
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700924int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700925 const std::string& sandboxId, userid_t userId) {
926 if (!GetBoolProperty(kIsolatedStorage, false)) {
927 return 0;
928 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700929 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
930 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700931 auto& userPackages = mUserPackages[userId];
Sudheer Shankaba0c62f2018-12-16 18:22:34 -0800932 userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
933 userPackages.end());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700934 // If the package is not uninstalled in any other users, remove appId and sandboxId
935 // corresponding to it from the internal state.
936 bool installedInAnyUser = false;
937 for (auto& it : mUserPackages) {
938 auto& packages = it.second;
939 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
940 installedInAnyUser = true;
941 break;
942 }
943 }
944 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700945 const auto& entry = mAppIds.find(packageName);
946 if (entry != mAppIds.end()) {
947 mSandboxIds.erase(entry->second);
948 mAppIds.erase(entry);
949 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700950 }
951
952 std::vector<std::string> visibleVolLabels;
953 for (auto& volId : mVisibleVolumeIds) {
954 auto vol = findVolume(volId);
955 userid_t mountUserId = vol->getMountUserId();
956 if (mountUserId == userId || vol->isEmulated()) {
957 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
958 return -errno;
959 }
960 }
961 }
962 return 0;
963}
964
965int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
966 const std::string& sandboxId, userid_t userId,
967 const std::string& volLabel) {
968 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
969 << ", volLabel=" << volLabel;
970 std::string pkgSandboxTarget =
971 StringPrintf("/mnt/user/%d/package/%s", userId, packageName.c_str());
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800972 if (android::vold::UnmountTreeWithPrefix(pkgSandboxTarget) < 0) {
973 PLOG(ERROR) << "UnmountTreeWithPrefix failed on " << pkgSandboxTarget;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700974 }
975
976 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
977 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
978 StringAppendF(&sandboxDir, "/%d", userId);
979 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700980 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700981
982 if (android::vold::DeleteDirContentsAndDir(sandboxDir) < 0) {
983 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
984 return -errno;
985 }
986 return 0;
987}
988
Jeff Sharkey401b2602017-12-14 22:15:20 -0700989int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
990 mSecureKeyguardShowing = isShowing;
991 if (!mSecureKeyguardShowing) {
992 // Now that secure keyguard has been dismissed, process
993 // any pending disks
994 for (const auto& disk : mPendingDisks) {
995 disk->create();
996 mDisks.push_back(disk);
997 }
998 mPendingDisks.clear();
999 }
1000 return 0;
1001}
1002
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001003int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
1004 if (!GetBoolProperty(kIsolatedStorage, false)) {
1005 return 0;
1006 }
1007
1008 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
1009 return 0;
1010 }
1011
1012 mVisibleVolumeIds.insert(vol->getId());
1013 userid_t mountUserId = vol->getMountUserId();
1014 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1015 // We don't want to create another shared_ptr here because then we will end up with
1016 // two shared_ptrs owning the underlying pointer without sharing it.
1017 mPrimary = findVolume(vol->getId());
1018 for (userid_t userId : mStartedUsers) {
1019 if (linkPrimary(userId) != 0) {
1020 return -errno;
1021 }
1022 }
1023 }
1024 if (vol->isEmulated()) {
1025 for (userid_t userId : mStartedUsers) {
1026 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
1027 return -errno;
1028 }
1029 }
1030 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1031 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
1032 return -errno;
1033 }
1034 }
1035 return 0;
1036}
1037
1038int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
1039 if (!GetBoolProperty(kIsolatedStorage, false)) {
1040 return 0;
1041 }
1042
1043 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
1044 return 0;
1045 }
1046
1047 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1048 mPrimary = nullptr;
1049 }
1050
1051 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
1052 userid_t mountUserId = vol->getMountUserId();
1053 if (vol->isEmulated()) {
1054 for (userid_t userId : mStartedUsers) {
1055 if (destroySandboxesForVol(vol, userId) != 0) {
1056 return -errno;
1057 }
1058 }
1059 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1060 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1061 return -errno;
1062 }
1063 }
1064 return 0;
1065}
1066
1067int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1068 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
1069 const std::vector<std::string>& packageNames = mUserPackages[userId];
1070 for (auto& packageName : packageNames) {
1071 std::string volSandboxRoot = StringPrintf("/mnt/user/%d/package/%s/%s", userId,
1072 packageName.c_str(), vol->getLabel().c_str());
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001073 if (android::vold::UnmountTreeWithPrefix(volSandboxRoot) < 0) {
1074 PLOG(ERROR) << "UnmountTreeWithPrefix on " << volSandboxRoot << " failed";
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001075 continue;
1076 }
1077 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1078 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1079 continue;
1080 }
1081 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
1082 }
1083 return 0;
1084}
1085
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001086int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001087 if (GetBoolProperty(kIsolatedStorage, false)) {
1088 return 0;
1089 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001090 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001091 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001092 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001093 }
1094 return 0;
1095}
1096
Sudheer Shanka817b9112018-12-13 17:40:28 -08001097int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
1098 if (!GetBoolProperty(kIsolatedStorage, false)) {
1099 return remountUidLegacy(uid, mountMode);
1100 }
1101
1102 appid_t appId = multiuser_get_app_id(uid);
1103 userid_t userId = multiuser_get_user_id(uid);
1104 std::vector<std::string> visibleVolLabels;
1105 for (auto& volId : mVisibleVolumeIds) {
1106 auto vol = findVolume(volId);
1107 userid_t mountUserId = vol->getMountUserId();
1108 if (mountUserId == userId || vol->isEmulated()) {
1109 visibleVolLabels.push_back(vol->getLabel());
1110 }
1111 }
1112
1113 // Finding one package with appId is enough
1114 std::vector<std::string> packageNames;
1115 for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
1116 if (it->second == appId) {
1117 packageNames.push_back(it->first);
1118 break;
1119 }
1120 }
1121 if (packageNames.empty()) {
1122 PLOG(ERROR) << "Failed to find packageName for " << uid;
Sudheer Shanka53947a32018-08-01 10:24:13 -07001123 return -1;
1124 }
Sudheer Shanka817b9112018-12-13 17:40:28 -08001125 return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
1126}
1127
1128int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
1129 std::string mode;
1130 switch (mountMode) {
1131 case VoldNativeService::REMOUNT_MODE_NONE:
1132 mode = "none";
1133 break;
1134 case VoldNativeService::REMOUNT_MODE_DEFAULT:
1135 mode = "default";
1136 break;
1137 case VoldNativeService::REMOUNT_MODE_READ:
1138 mode = "read";
1139 break;
1140 case VoldNativeService::REMOUNT_MODE_WRITE:
1141 mode = "write";
1142 break;
1143 default:
1144 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
1145 return -1;
1146 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001147 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1148
1149 DIR* dir;
1150 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001151 std::string rootName;
1152 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001153 int pidFd;
1154 int nsFd;
1155 struct stat sb;
1156 pid_t child;
1157
1158 if (!(dir = opendir("/proc"))) {
1159 PLOG(ERROR) << "Failed to opendir";
1160 return -1;
1161 }
1162
1163 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001164 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1165 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001166 closedir(dir);
1167 return -1;
1168 }
1169
1170 // Poke through all running PIDs look for apps running as UID
1171 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001172 pid_t pid;
1173 if (de->d_type != DT_DIR) continue;
1174 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1175
Jeff Sharkey66270a22015-06-24 11:49:24 -07001176 pidFd = -1;
1177 nsFd = -1;
1178
1179 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1180 if (pidFd < 0) {
1181 goto next;
1182 }
1183 if (fstat(pidFd, &sb) != 0) {
1184 PLOG(WARNING) << "Failed to stat " << de->d_name;
1185 goto next;
1186 }
1187 if (sb.st_uid != uid) {
1188 goto next;
1189 }
1190
1191 // Matches so far, but refuse to touch if in root namespace
1192 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001193 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001194 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1195 goto next;
1196 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001197 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001198 LOG(WARNING) << "Skipping due to root namespace";
1199 goto next;
1200 }
1201
1202 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001203 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -07001204 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001205 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001206 goto next;
1207 }
1208
1209 if (!(child = fork())) {
1210 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001211 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001212 _exit(1);
1213 }
1214
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001215 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001216
1217 std::string storageSource;
1218 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001219 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001220 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001221 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001222 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001223 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001224 } else {
1225 // Sane default of no storage visible
1226 _exit(0);
1227 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001228 if (TEMP_FAILURE_RETRY(
1229 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1230 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001231 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001232 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001233 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1234 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001235 _exit(1);
1236 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001237
1238 // Mount user-specific symlink helper into place
1239 userid_t user_id = multiuser_get_user_id(uid);
1240 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001241 if (TEMP_FAILURE_RETRY(
1242 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1243 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001244 _exit(1);
1245 }
1246
Jeff Sharkey66270a22015-06-24 11:49:24 -07001247 _exit(0);
1248 }
1249
1250 if (child == -1) {
1251 PLOG(ERROR) << "Failed to fork";
1252 goto next;
1253 } else {
1254 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1255 }
1256
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001257 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001258 close(nsFd);
1259 close(pidFd);
1260 }
1261 closedir(dir);
1262 return 0;
1263}
1264
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001265int VolumeManager::reset() {
1266 // Tear down all existing disks/volumes and start from a blank slate so
1267 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001268 if (mInternalEmulated != nullptr) {
1269 mInternalEmulated->destroy();
1270 mInternalEmulated->create();
1271 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001272 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001273 disk->destroy();
1274 disk->create();
1275 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001276 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001277 mAddedUsers.clear();
1278 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001279
1280 mUserPackages.clear();
1281 mAppIds.clear();
1282 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001283 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001284
1285 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001286 android::vold::UnmountTreeWithPrefix("/mnt/user/");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001287 return 0;
1288}
1289
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001290// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001291int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001292 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001293 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001294 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001295 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001296 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001297 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001298 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001299 disk->destroy();
1300 }
Risan8c9f3322018-10-29 08:52:56 +09001301 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001302 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001303 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001304 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001305 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001306}
1307
Jeff Sharkey9c484982015-03-31 10:35:33 -07001308int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001309 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001310 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001311
Jeff Sharkey9c484982015-03-31 10:35:33 -07001312 // First, try gracefully unmounting all known devices
1313 if (mInternalEmulated != nullptr) {
1314 mInternalEmulated->unmount();
1315 }
Risan8c9f3322018-10-29 08:52:56 +09001316 for (const auto& stub : mStubVolumes) {
1317 stub->unmount();
1318 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001319 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001320 disk->unmountAll();
1321 }
1322
1323 // Worst case we might have some stale mounts lurking around, so
1324 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001325 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001326 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001327 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001328 return -errno;
1329 }
1330
1331 // Some volumes can be stacked on each other, so force unmount in
1332 // reverse order to give us the best chance of success.
1333 std::list<std::string> toUnmount;
1334 mntent* mentry;
1335 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001336 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001337 if ((StartsWith(test, "/mnt/") &&
1338#ifdef __ANDROID_DEBUGGABLE__
1339 !StartsWith(test, "/mnt/scratch") &&
1340#endif
1341 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1342 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001343 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001344 }
1345 }
1346 endmntent(fp);
1347
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001348 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001349 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001350 android::vold::ForceUnmount(path);
1351 }
1352
1353 return 0;
1354}
1355
Jeff Sharkey3472e522017-10-06 18:02:53 -06001356int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001357 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001358 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001359 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001360 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001361 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001362 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001363 return -EINVAL;
1364 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001365}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001366
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001367int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001368 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001369 int id = mNextObbId++;
1370
1371 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001372 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001373 vol->create();
1374
1375 mObbVolumes.push_back(vol);
1376 *outVolId = vol->getId();
1377 return android::OK;
1378}
1379
1380int VolumeManager::destroyObb(const std::string& volId) {
1381 auto i = mObbVolumes.begin();
1382 while (i != mObbVolumes.end()) {
1383 if ((*i)->getId() == volId) {
1384 (*i)->destroy();
1385 i = mObbVolumes.erase(i);
1386 } else {
1387 ++i;
1388 }
1389 }
1390 return android::OK;
1391}
1392
Risan8c9f3322018-10-29 08:52:56 +09001393int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1394 const std::string& fsType, const std::string& fsUuid,
1395 const std::string& fsLabel, std::string* outVolId) {
1396 int id = mNextStubVolumeId++;
1397 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1398 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1399 vol->create();
1400
1401 mStubVolumes.push_back(vol);
1402 *outVolId = vol->getId();
1403 return android::OK;
1404}
1405
1406int VolumeManager::destroyStubVolume(const std::string& volId) {
1407 auto i = mStubVolumes.begin();
1408 while (i != mStubVolumes.end()) {
1409 if ((*i)->getId() == volId) {
1410 (*i)->destroy();
1411 i = mStubVolumes.erase(i);
1412 } else {
1413 ++i;
1414 }
1415 }
1416 return android::OK;
1417}
1418
Risan8f6198d2018-10-26 20:56:45 -06001419int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001420 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001421}
1422
Risan8f6198d2018-10-26 20:56:45 -06001423int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001424 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001425}
1426
1427int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001428 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001429}