blob: db098e387a355c2f55f33a850729b64b2b8b146a [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 Shanka023b5392019-02-06 12:39:19 -080076using android::vold::BindMount;
77using android::vold::DeleteDirContentsAndDir;
78using android::vold::Symlink;
79using android::vold::Unlink;
80using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080081using android::vold::VoldNativeService;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070082
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060083static const char* kPathUserMount = "/mnt/user";
84static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
85
Sudheer Shanka53947a32018-08-01 10:24:13 -070086static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Sudheer Shanka34b437b2019-01-17 17:20:47 -080087static const char* kIsolatedStorageSnapshot = "sys.isolated_storage_snapshot";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060088static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
89
Sudheer Shanka53947a32018-08-01 10:24:13 -070090static const std::string kEmptyString("");
91
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060092/* 512MiB is large enough for testing purposes */
93static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070094
Jeff Sharkey36801cc2015-03-13 16:09:20 -070095static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080096static const unsigned int kMajorBlockExperimentalMin = 240;
97static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070098
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070099VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700100
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700101VolumeManager* VolumeManager::Instance() {
102 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700103 return sInstance;
104}
105
106VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800107 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600108 mNextObbId = 0;
Risan8c9f3322018-10-29 08:52:56 +0900109 mNextStubVolumeId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700110 // For security reasons, assume that a secure keyguard is
111 // showing until we hear otherwise
112 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700113}
114
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700115VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800116
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800117static bool hasIsolatedStorage() {
Jeff Sharkeya6082502019-02-11 12:18:48 -0700118 return GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, true));
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800119}
120
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600121int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600122 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700123 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600124 if (access(kPathVirtualDisk, F_OK) != 0) {
125 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
126 }
127
128 if (mVirtualDisk == nullptr) {
129 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
130 LOG(ERROR) << "Failed to create virtual disk";
131 return -1;
132 }
133
134 struct stat buf;
135 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
136 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
137 return -1;
138 }
139
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700140 auto disk = new android::vold::Disk(
141 "virtual", buf.st_rdev, "virtual",
142 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600143 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700144 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600145 }
146 } else {
147 if (mVirtualDisk != nullptr) {
148 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700149 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600150
151 Loop::destroyByDevice(mVirtualDiskPath.c_str());
152 mVirtualDisk = nullptr;
153 }
154
155 if (access(kPathVirtualDisk, F_OK) == 0) {
156 unlink(kPathVirtualDisk);
157 }
158 }
159 return 0;
160}
161
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700162int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800163 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700164 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800165}
166
San Mehatf1b736b2009-10-10 17:22:08 -0700167int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600168 ATRACE_NAME("VolumeManager::start");
169
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700170 // Always start from a clean slate by unmounting everything in
171 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700172 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700173
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600174 Devmapper::destroyAll();
175 Loop::destroyAll();
176
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 // Assume that we always have an emulated volume on internal
178 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700179 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700180 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700181 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700182 mInternalEmulated->create();
183
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600184 // Consider creating a virtual disk
185 updateVirtualDisk();
186
San Mehatf1b736b2009-10-10 17:22:08 -0700187 return 0;
188}
189
190int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700191 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192 mInternalEmulated->destroy();
193 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700194 return 0;
195}
196
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700197void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700198 std::lock_guard<std::mutex> lock(mLock);
199
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700200 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700201 LOG(DEBUG) << "----------------";
202 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700203 evt->dump();
204 }
San Mehatf1b736b2009-10-10 17:22:08 -0700205
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700206 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
207 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700208
209 if (devType != "disk") return;
210
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600211 int major = std::stoi(evt->findParam("MAJOR"));
212 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700213 dev_t device = makedev(major, minor);
214
215 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700216 case NetlinkEvent::Action::kAdd: {
217 for (const auto& source : mDiskSources) {
218 if (source->matches(eventPath)) {
219 // For now, assume that MMC and virtio-blk (the latter is
220 // emulator-specific; see Disk.cpp for details) devices are SD,
221 // and that everything else is USB
222 int flags = source->getFlags();
223 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
224 major >= (int)kMajorBlockExperimentalMin &&
225 major <= (int)kMajorBlockExperimentalMax)) {
226 flags |= android::vold::Disk::Flags::kSd;
227 } else {
228 flags |= android::vold::Disk::Flags::kUsb;
229 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700230
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700231 auto disk =
232 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
233 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
234 break;
235 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700236 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700237 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700239 case NetlinkEvent::Action::kChange: {
240 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
241 handleDiskChanged(device);
242 break;
243 }
244 case NetlinkEvent::Action::kRemove: {
245 handleDiskRemoved(device);
246 break;
247 }
248 default: {
249 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
250 break;
251 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700252 }
253}
254
Jeff Sharkey401b2602017-12-14 22:15:20 -0700255void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
256 // For security reasons, if secure keyguard is showing, wait
257 // until the user unlocks the device to actually touch it
258 if (mSecureKeyguardShowing) {
259 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700260 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700261 mPendingDisks.push_back(disk);
262 } else {
263 disk->create();
264 mDisks.push_back(disk);
265 }
266}
267
268void VolumeManager::handleDiskChanged(dev_t device) {
269 for (const auto& disk : mDisks) {
270 if (disk->getDevice() == device) {
271 disk->readMetadata();
272 disk->readPartitions();
273 }
274 }
275
276 // For security reasons, we ignore all pending disks, since
277 // we'll scan them once the device is unlocked
278}
279
280void VolumeManager::handleDiskRemoved(dev_t device) {
281 auto i = mDisks.begin();
282 while (i != mDisks.end()) {
283 if ((*i)->getDevice() == device) {
284 (*i)->destroy();
285 i = mDisks.erase(i);
286 } else {
287 ++i;
288 }
289 }
290 auto j = mPendingDisks.begin();
291 while (j != mPendingDisks.end()) {
292 if ((*j)->getDevice() == device) {
293 j = mPendingDisks.erase(j);
294 } else {
295 ++j;
296 }
297 }
298}
299
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700300void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800301 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700302 mDiskSources.push_back(diskSource);
303}
304
305std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
306 for (auto disk : mDisks) {
307 if (disk->getId() == id) {
308 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700309 }
310 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700311 return nullptr;
312}
San Mehatf1b736b2009-10-10 17:22:08 -0700313
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700314std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800315 // Vold could receive "mount" after "shutdown" command in the extreme case.
316 // If this happens, mInternalEmulated will equal nullptr and
317 // we need to deal with it in order to avoid null pointer crash.
318 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700319 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700320 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700321 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700322 auto vol = disk->findVolume(id);
323 if (vol != nullptr) {
324 return vol;
325 }
326 }
Risan8c9f3322018-10-29 08:52:56 +0900327 for (const auto& vol : mStubVolumes) {
328 if (vol->getId() == id) {
329 return vol;
330 }
331 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600332 for (const auto& vol : mObbVolumes) {
333 if (vol->getId() == id) {
334 return vol;
335 }
336 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700337 return nullptr;
338}
339
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800340void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
341 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700342 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700343 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700344 disk->listVolumes(type, list);
345 }
346}
347
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600348int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700349 std::string normalizedGuid;
350 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
351 LOG(WARNING) << "Invalid GUID " << partGuid;
352 return -1;
353 }
354
Paul Crowleyc6433a22017-10-24 14:54:43 -0700355 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700356 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
357 if (unlink(keyPath.c_str()) != 0) {
358 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700359 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700360 }
Eric Biggersa701c452018-10-23 13:06:55 -0700361 if (fscrypt_is_native()) {
362 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700363 success = false;
364 }
365 }
366 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700367}
368
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700369int VolumeManager::linkPrimary(userid_t userId) {
370 std::string source(mPrimary->getPath());
371 if (mPrimary->isEmulated()) {
372 source = StringPrintf("%s/%d", source.c_str(), userId);
373 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
374 }
375
376 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700377 LOG(DEBUG) << "Linking " << source << " to " << target;
Sudheer Shanka023b5392019-02-06 12:39:19 -0800378 Symlink(source, target);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700379 return 0;
380}
381
382int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
383 const std::string& mntTargetRoot,
384 const std::string& packageName, const char* dirName) {
385 std::string mntSourceDir =
386 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
387 std::string mntTargetDir =
388 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
Sudheer Shanka023b5392019-02-06 12:39:19 -0800389 return BindMount(mntSourceDir, mntTargetDir);
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700390}
391
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700392int VolumeManager::mountPkgSpecificDirsForRunningProcs(
393 userid_t userId, const std::vector<std::string>& packageNames,
Sudheer Shanka817b9112018-12-13 17:40:28 -0800394 const std::vector<std::string>& visibleVolLabels, int remountMode) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700395 // TODO: New processes could be started while traversing over the existing
396 // processes which would end up not having the necessary bind mounts. This
397 // issue needs to be fixed, may be by doing multiple passes here?
398 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
399 if (!dirp) {
400 PLOG(ERROR) << "Failed to opendir /proc";
401 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700402 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700403
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700404 std::string rootName;
405 // Figure out root namespace to compare against below
406 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
407 PLOG(ERROR) << "Failed to read root namespace";
408 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700409 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700410
Sudheer Shanka55049012019-01-09 12:15:15 -0800411 struct stat mntFullSb;
412 struct stat mntWriteSb;
413 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/full", &mntFullSb)) == -1) {
414 PLOG(ERROR) << "Failed to stat /mnt/runtime/full";
415 return -1;
416 }
417 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &mntWriteSb)) == -1) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700418 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
419 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700420 }
421
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700422 std::unordered_set<appid_t> validAppIds;
423 for (auto& package : packageNames) {
424 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700425 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700426 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700427
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700428 struct dirent* de;
429 // Poke through all running PIDs look for apps running in userId
430 while ((de = readdir(dirp.get()))) {
431 pid_t pid;
432 if (de->d_type != DT_DIR) continue;
433 if (!android::base::ParseInt(de->d_name, &pid)) continue;
434
435 const unique_fd pidFd(
436 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
437 if (pidFd.get() < 0) {
438 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700439 continue;
440 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700441 struct stat sb;
442 if (fstat(pidFd.get(), &sb) != 0) {
443 PLOG(WARNING) << "Failed to stat " << de->d_name;
444 continue;
445 }
446 if (multiuser_get_user_id(sb.st_uid) != userId) {
447 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700448 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700449
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700450 // Matches so far, but refuse to touch if in root namespace
451 LOG(VERBOSE) << "Found matching PID " << de->d_name;
452 std::string pidName;
453 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
454 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
455 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700456 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700457 if (rootName == pidName) {
458 LOG(WARNING) << "Skipping due to root namespace";
459 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700460 }
461
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700462 // Only update the mount points of processes running with one of validAppIds.
463 // This should skip any isolated uids.
464 appid_t appId = multiuser_get_app_id(sb.st_uid);
465 if (validAppIds.find(appId) == validAppIds.end()) {
466 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700467 }
468
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700469 std::vector<std::string> packagesForUid;
470 for (auto& package : userPackages) {
471 if (mAppIds[package] == appId) {
472 packagesForUid.push_back(package);
473 }
474 }
475 if (packagesForUid.empty()) {
476 continue;
477 }
478 const std::string& sandboxId = mSandboxIds[appId];
479
480 // We purposefully leave the namespace open across the fork
481 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
482 if (nsFd.get() < 0) {
483 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
484 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700485 }
486
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700487 pid_t child;
488 if (!(child = fork())) {
489 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
490 PLOG(ERROR) << "Failed to setns for " << de->d_name;
491 _exit(1);
492 }
493
Sudheer Shanka817b9112018-12-13 17:40:28 -0800494 int mountMode;
495 if (remountMode == -1) {
Sudheer Shanka55049012019-01-09 12:15:15 -0800496 mountMode =
497 getMountModeForRunningProc(packagesForUid, userId, mntWriteSb, mntFullSb);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800498 if (mountMode == -1) {
499 _exit(1);
500 }
501 } else {
502 mountMode = remountMode;
503 std::string obbMountFile = StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId,
504 packagesForUid[0].c_str());
505 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
506 if (access(obbMountFile.c_str(), F_OK) != 0) {
507 const unique_fd fd(
508 TEMP_FAILURE_RETRY(open(obbMountFile.c_str(), O_RDWR | O_CREAT, 0660)));
509 }
510 } else {
511 if (access(obbMountFile.c_str(), F_OK) == 0) {
512 remove(obbMountFile.c_str());
513 }
514 }
515 }
516 if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
Sudheer Shanka55049012019-01-09 12:15:15 -0800517 mountMode == VoldNativeService::REMOUNT_MODE_LEGACY ||
Sudheer Shanka817b9112018-12-13 17:40:28 -0800518 mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
519 // These mount modes are not going to change dynamically, so don't bother
520 // unmounting/remounting dirs.
521 _exit(0);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700522 }
523
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700524 for (auto& volumeLabel : visibleVolLabels) {
525 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
526 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
527 if (volumeLabel == "emulated") {
528 StringAppendF(&mntSource, "/%d", userId);
529 StringAppendF(&mntTarget, "/%d", userId);
530 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800531
532 std::string sandboxSource =
533 StringPrintf("%s/Android/sandbox/%s", mntSource.c_str(), sandboxId.c_str());
534 if (BindMount(sandboxSource, mntTarget) < 0) {
535 continue;
536 }
537
Sudheer Shanka817b9112018-12-13 17:40:28 -0800538 std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
539 std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
Sudheer Shanka023b5392019-02-06 12:39:19 -0800540 if (UnmountTree(obbTargetDir) < 0) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800541 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 Shanka023b5392019-02-06 12:39:19 -0800551 if (BindMount(obbSourceDir, obbTargetDir) < 0) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800552 continue;
553 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700554 }
555 }
556 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700557 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700558
559 if (child == -1) {
560 PLOG(ERROR) << "Failed to fork";
561 } else {
562 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700563 }
564 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700565 return 0;
566}
567
Sudheer Shanka03992e32018-12-12 12:43:38 -0800568int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
Sudheer Shanka55049012019-01-09 12:15:15 -0800569 userid_t userId, struct stat& mntWriteStat,
570 struct stat& mntFullStat) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800571 struct stat storageSb;
572 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
573 PLOG(ERROR) << "Failed to stat /storage";
574 return -1;
575 }
576
577 // Some packages have access to full external storage, identify processes belonging
Sudheer Shanka55049012019-01-09 12:15:15 -0800578 // to those packages by comparing inode no.s of /mnt/runtime/full and /storage
579 if (storageSb.st_dev == mntFullStat.st_dev && storageSb.st_ino == mntFullStat.st_ino) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800580 return VoldNativeService::REMOUNT_MODE_FULL;
Sudheer Shanka55049012019-01-09 12:15:15 -0800581 } else if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
582 return VoldNativeService::REMOUNT_MODE_LEGACY;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800583 }
584
585 std::string obbMountFile =
586 StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId, packagesForUid[0].c_str());
587 if (access(obbMountFile.c_str(), F_OK) == 0) {
588 return VoldNativeService::REMOUNT_MODE_INSTALLER;
589 }
590
591 // Some packages don't have access to external storage and processes belonging to
592 // those packages don't have anything mounted at /storage. So, identify those
593 // processes by comparing inode no.s of /mnt/user/%d/package/%s
594 // and /storage
595 for (auto& package : packagesForUid) {
596 std::string sandbox = StringPrintf("/mnt/user/%d/package/%s", userId, package.c_str());
597 struct stat sandboxStat;
598 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
599 PLOG(ERROR) << "Failed to stat " << sandbox;
600 return -1;
601 }
602 if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
603 return VoldNativeService::REMOUNT_MODE_WRITE;
604 }
605 }
606 return VoldNativeService::REMOUNT_MODE_NONE;
607}
608
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700609int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
610 const std::vector<std::string>& visibleVolLabels) {
611 if (visibleVolLabels.empty()) {
612 return 0;
613 }
614 for (auto& volumeLabel : visibleVolLabels) {
615 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
616 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
617 if (isVolPrimaryEmulated) {
618 StringAppendF(&volumeRoot, "/%d", userId);
619 if (fs_prepare_dir(volumeRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
620 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeRoot;
621 return -errno;
622 }
623 }
624
625 std::string sandboxRoot =
626 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
627 if (sandboxRoot.empty()) {
628 return -errno;
629 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700630
631 if (!createPkgSpecificDirRoots(volumeRoot)) {
632 return -errno;
633 }
634
635 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
636 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
637 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
638 return -errno;
639 }
640 mntTargetRoot.append("/package");
641 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
642 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
643 return -errno;
644 }
645
646 for (auto& packageName : packageNames) {
647 const auto& it = mAppIds.find(packageName);
648 if (it == mAppIds.end()) {
649 PLOG(ERROR) << "appId is not available for " << packageName;
650 continue;
651 }
652 appid_t appId = it->second;
653 std::string sandboxId = mSandboxIds[appId];
654 uid_t uid = multiuser_get_uid(userId, appId);
655
656 // [1] Create /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
657 // [2] Create /mnt/user/0/package/<packageName>/emulated/0
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700658 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
659 if (pkgSandboxSourceDir.empty()) {
660 return -errno;
661 }
662 std::string pkgSandboxTargetDir = prepareSandboxTarget(
663 packageName, uid, volumeLabel, mntTargetRoot, isVolPrimaryEmulated);
664 if (pkgSandboxTargetDir.empty()) {
665 return -errno;
666 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700667
668 // Create Android/{data,media,obb}/<packageName> segments at
669 // [1] /mnt/runtime/write/emulated/0/ and
670 // [2] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>/emulated/0/
671 if (!createPkgSpecificDirs(packageName, uid, volumeRoot, pkgSandboxSourceDir)) {
672 return -errno;
673 }
674
675 if (volumeLabel == mPrimary->getLabel()) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800676 // [1] Create /mnt/user/0/package/<packageName>/self/
677 // Link [1] to /storage/emulated/0
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700678 std::string pkgPrimaryTargetDir =
679 StringPrintf("%s/%s/self", mntTargetRoot.c_str(), packageName.c_str());
680 if (fs_prepare_dir(pkgPrimaryTargetDir.c_str(), 0755, uid, uid) != 0) {
681 PLOG(ERROR) << "Failed to fs_prepare_dir on " << pkgPrimaryTargetDir;
682 return -errno;
683 }
684 StringAppendF(&pkgPrimaryTargetDir, "/primary");
685 std::string primarySource(mPrimary->getPath());
686 if (isVolPrimaryEmulated) {
687 StringAppendF(&primarySource, "/%d", userId);
688 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800689 Symlink(primarySource, pkgPrimaryTargetDir);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700690 }
691 }
692 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800693 mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700694 return 0;
695}
696
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700697std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
698 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700699 std::string path(pathPrefix);
700 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
701 for (size_t i = 0; i < subDirList.size(); ++i) {
702 std::string subDir = subDirList[i];
703 if (subDir.empty()) {
704 continue;
705 }
706 StringAppendF(&path, "/%s", subDir.c_str());
707 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
708 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
709 return kEmptyString;
710 }
711 }
712 return path;
713}
714
715std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700716 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700717 std::string sandboxSourceDir(sandboxRootDir);
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700718 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700719 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
720 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
721 return kEmptyString;
722 }
723 return sandboxSourceDir;
724}
725
726std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700727 const std::string& volumeLabel,
728 const std::string& mntTargetRootDir,
729 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700730 std::string segment;
731 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700732 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
733 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700734 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700735 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700736 }
737 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
738}
739
740std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700741 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700742 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
743 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
744 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
745 return kEmptyString;
746 }
747 return dataSourceDir;
748}
749
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700750bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
751 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
752 if (fs_prepare_dir(volumeAndroidRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
753 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeAndroidRoot;
754 return false;
755 }
756 std::array<std::string, 3> dirs = {"data", "media", "obb"};
757 for (auto& dir : dirs) {
758 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
759 if (fs_prepare_dir(path.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
760 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
761 return false;
762 }
763 }
764 return true;
765}
766
767bool VolumeManager::createPkgSpecificDirs(const std::string& packageName, uid_t uid,
768 const std::string& volumeRoot,
769 const std::string& sandboxDirRoot) {
770 std::array<std::string, 3> dirs = {"data", "media", "obb"};
771 for (auto& dir : dirs) {
772 std::string sourceDir = StringPrintf("%s/Android/%s", volumeRoot.c_str(), dir.c_str());
773 if (prepareSubDirs(sourceDir, packageName, 0755, uid, uid).empty()) {
774 return false;
775 }
776 std::string sandboxSegment =
777 StringPrintf("Android/%s/%s/", dir.c_str(), packageName.c_str());
778 if (prepareSubDirs(sandboxDirRoot, sandboxSegment, 0755, uid, uid).empty()) {
779 return false;
780 }
781 }
782 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700783}
784
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700785int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
786 mAddedUsers[userId] = userSerialNumber;
787 return 0;
788}
789
790int VolumeManager::onUserRemoved(userid_t userId) {
791 mAddedUsers.erase(userId);
792 return 0;
793}
794
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700795int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
796 const std::vector<int>& appIds,
797 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700798 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700799 // Note that sometimes the system will spin up processes from Zygote
800 // before actually starting the user, so we're okay if Zygote
801 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600802 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700803 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
804
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700805 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700806 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700807 for (size_t i = 0; i < packageNames.size(); ++i) {
808 mAppIds[packageNames[i]] = appIds[i];
809 mSandboxIds[appIds[i]] = sandboxIds[i];
810 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700811 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700812 linkPrimary(userId);
813 }
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800814 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700815 std::vector<std::string> visibleVolLabels;
816 for (auto& volId : mVisibleVolumeIds) {
817 auto vol = findVolume(volId);
818 userid_t mountUserId = vol->getMountUserId();
819 if (mountUserId == userId || vol->isEmulated()) {
820 visibleVolLabels.push_back(vol->getLabel());
821 }
822 }
823 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
824 return -errno;
825 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700826 }
827 return 0;
828}
829
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700830int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700831 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700832 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700833
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800834 if (hasIsolatedStorage()) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800835 auto& userPackages = mUserPackages[userId];
836 std::string userMntTargetRoot = StringPrintf("/mnt/user/%d", userId);
837 for (auto& package : userPackages) {
838 std::string pkgPrimaryDir = StringPrintf("%s/package/%s/self/primary",
839 userMntTargetRoot.c_str(), package.c_str());
840 if (Unlink(pkgPrimaryDir) < 0) {
841 return -errno;
842 }
843 }
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700844 mUserPackages.erase(userId);
Sudheer Shanka023b5392019-02-06 12:39:19 -0800845 if (DeleteDirContentsAndDir(userMntTargetRoot) < 0) {
846 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << userMntTargetRoot;
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700847 return -errno;
848 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800849 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << userMntTargetRoot;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700850 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700851 return 0;
852}
853
Sudheer Shankad484aa92018-07-31 10:07:34 -0700854int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700855 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700856 for (size_t i = 0; i < packageNames.size(); ++i) {
857 mAppIds[packageNames[i]] = appIds[i];
858 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700859 return 0;
860}
861
862int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700863 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700864 for (size_t i = 0; i < appIds.size(); ++i) {
865 mSandboxIds[appIds[i]] = sandboxIds[i];
866 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700867 return 0;
868}
869
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700870int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
871 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800872 if (!hasIsolatedStorage()) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700873 return 0;
874 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
875 // User not started, no need to do anything now. Required bind mounts for the package will
876 // be created when the user starts.
877 return 0;
878 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700879 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700880 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700881 mUserPackages[userId].push_back(packageName);
882 mAppIds[packageName] = appId;
883 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700884
885 std::vector<std::string> visibleVolLabels;
886 for (auto& volId : mVisibleVolumeIds) {
887 auto vol = findVolume(volId);
888 userid_t mountUserId = vol->getMountUserId();
889 if (mountUserId == userId || vol->isEmulated()) {
890 visibleVolLabels.push_back(vol->getLabel());
891 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700892 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700893 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700894}
895
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700896int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700897 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800898 if (!hasIsolatedStorage()) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700899 return 0;
900 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700901 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
902 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700903 auto& userPackages = mUserPackages[userId];
Sudheer Shankaba0c62f2018-12-16 18:22:34 -0800904 userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
905 userPackages.end());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700906 // If the package is not uninstalled in any other users, remove appId and sandboxId
907 // corresponding to it from the internal state.
908 bool installedInAnyUser = false;
909 for (auto& it : mUserPackages) {
910 auto& packages = it.second;
911 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
912 installedInAnyUser = true;
913 break;
914 }
915 }
916 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700917 const auto& entry = mAppIds.find(packageName);
918 if (entry != mAppIds.end()) {
919 mSandboxIds.erase(entry->second);
920 mAppIds.erase(entry);
921 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700922 }
923
924 std::vector<std::string> visibleVolLabels;
925 for (auto& volId : mVisibleVolumeIds) {
926 auto vol = findVolume(volId);
927 userid_t mountUserId = vol->getMountUserId();
928 if (mountUserId == userId || vol->isEmulated()) {
929 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
930 return -errno;
931 }
932 }
933 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800934 std::string pkgMountTargetDir =
935 StringPrintf("/mnt/user/%d/package/%s", userId, packageName.c_str());
936 std::string pkgPrimaryDir = StringPrintf("%s/self/primary", pkgMountTargetDir.c_str());
937 if (Unlink(pkgPrimaryDir) < 0) {
938 return -errno;
939 }
940 DeleteDirContentsAndDir(pkgMountTargetDir);
941
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700942 return 0;
943}
944
945int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
946 const std::string& sandboxId, userid_t userId,
947 const std::string& volLabel) {
948 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
949 << ", volLabel=" << volLabel;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700950
951 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
952 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
953 StringAppendF(&sandboxDir, "/%d", userId);
954 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700955 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700956
Sudheer Shanka023b5392019-02-06 12:39:19 -0800957 if (DeleteDirContentsAndDir(sandboxDir) < 0) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700958 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
959 return -errno;
960 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800961
962 std::string pkgMountTargetDir =
963 StringPrintf("/mnt/user/%d/package/%s/%s", userId, packageName.c_str(), volLabel.c_str());
964 // It's okay if this fails
965 DeleteDirContentsAndDir(pkgMountTargetDir);
966
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700967 return 0;
968}
969
Jeff Sharkey401b2602017-12-14 22:15:20 -0700970int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
971 mSecureKeyguardShowing = isShowing;
972 if (!mSecureKeyguardShowing) {
973 // Now that secure keyguard has been dismissed, process
974 // any pending disks
975 for (const auto& disk : mPendingDisks) {
976 disk->create();
977 mDisks.push_back(disk);
978 }
979 mPendingDisks.clear();
980 }
981 return 0;
982}
983
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700984int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800985 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700986 return 0;
987 }
988
989 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
990 return 0;
991 }
992
993 mVisibleVolumeIds.insert(vol->getId());
994 userid_t mountUserId = vol->getMountUserId();
995 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
996 // We don't want to create another shared_ptr here because then we will end up with
997 // two shared_ptrs owning the underlying pointer without sharing it.
998 mPrimary = findVolume(vol->getId());
999 for (userid_t userId : mStartedUsers) {
1000 if (linkPrimary(userId) != 0) {
1001 return -errno;
1002 }
1003 }
1004 }
1005 if (vol->isEmulated()) {
1006 for (userid_t userId : mStartedUsers) {
1007 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
1008 return -errno;
1009 }
1010 }
1011 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1012 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
1013 return -errno;
1014 }
1015 }
1016 return 0;
1017}
1018
1019int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001020 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001021 return 0;
1022 }
1023
1024 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
1025 return 0;
1026 }
1027
1028 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1029 mPrimary = nullptr;
1030 }
1031
1032 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
1033 userid_t mountUserId = vol->getMountUserId();
1034 if (vol->isEmulated()) {
1035 for (userid_t userId : mStartedUsers) {
1036 if (destroySandboxesForVol(vol, userId) != 0) {
1037 return -errno;
1038 }
1039 }
1040 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1041 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1042 return -errno;
1043 }
1044 }
1045 return 0;
1046}
1047
1048int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1049 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
1050 const std::vector<std::string>& packageNames = mUserPackages[userId];
1051 for (auto& packageName : packageNames) {
1052 std::string volSandboxRoot = StringPrintf("/mnt/user/%d/package/%s/%s", userId,
1053 packageName.c_str(), vol->getLabel().c_str());
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001054 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1055 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1056 continue;
1057 }
1058 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
1059 }
1060 return 0;
1061}
1062
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001063int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001064 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001065 return 0;
1066 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001067 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001068 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001069 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001070 }
1071 return 0;
1072}
1073
Sudheer Shanka817b9112018-12-13 17:40:28 -08001074int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001075 if (!hasIsolatedStorage()) {
Sudheer Shanka817b9112018-12-13 17:40:28 -08001076 return remountUidLegacy(uid, mountMode);
1077 }
1078
1079 appid_t appId = multiuser_get_app_id(uid);
1080 userid_t userId = multiuser_get_user_id(uid);
1081 std::vector<std::string> visibleVolLabels;
1082 for (auto& volId : mVisibleVolumeIds) {
1083 auto vol = findVolume(volId);
1084 userid_t mountUserId = vol->getMountUserId();
1085 if (mountUserId == userId || vol->isEmulated()) {
1086 visibleVolLabels.push_back(vol->getLabel());
1087 }
1088 }
1089
1090 // Finding one package with appId is enough
1091 std::vector<std::string> packageNames;
1092 for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
1093 if (it->second == appId) {
1094 packageNames.push_back(it->first);
1095 break;
1096 }
1097 }
1098 if (packageNames.empty()) {
1099 PLOG(ERROR) << "Failed to find packageName for " << uid;
Sudheer Shanka53947a32018-08-01 10:24:13 -07001100 return -1;
1101 }
Sudheer Shanka817b9112018-12-13 17:40:28 -08001102 return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
1103}
1104
1105int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
1106 std::string mode;
1107 switch (mountMode) {
1108 case VoldNativeService::REMOUNT_MODE_NONE:
1109 mode = "none";
1110 break;
1111 case VoldNativeService::REMOUNT_MODE_DEFAULT:
1112 mode = "default";
1113 break;
1114 case VoldNativeService::REMOUNT_MODE_READ:
1115 mode = "read";
1116 break;
1117 case VoldNativeService::REMOUNT_MODE_WRITE:
1118 mode = "write";
1119 break;
1120 default:
1121 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
1122 return -1;
1123 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001124 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1125
1126 DIR* dir;
1127 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001128 std::string rootName;
1129 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001130 int pidFd;
1131 int nsFd;
1132 struct stat sb;
1133 pid_t child;
1134
1135 if (!(dir = opendir("/proc"))) {
1136 PLOG(ERROR) << "Failed to opendir";
1137 return -1;
1138 }
1139
1140 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001141 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1142 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001143 closedir(dir);
1144 return -1;
1145 }
1146
1147 // Poke through all running PIDs look for apps running as UID
1148 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001149 pid_t pid;
1150 if (de->d_type != DT_DIR) continue;
1151 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1152
Jeff Sharkey66270a22015-06-24 11:49:24 -07001153 pidFd = -1;
1154 nsFd = -1;
1155
1156 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1157 if (pidFd < 0) {
1158 goto next;
1159 }
1160 if (fstat(pidFd, &sb) != 0) {
1161 PLOG(WARNING) << "Failed to stat " << de->d_name;
1162 goto next;
1163 }
1164 if (sb.st_uid != uid) {
1165 goto next;
1166 }
1167
1168 // Matches so far, but refuse to touch if in root namespace
1169 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001170 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001171 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1172 goto next;
1173 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001174 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001175 LOG(WARNING) << "Skipping due to root namespace";
1176 goto next;
1177 }
1178
1179 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001180 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -07001181 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001182 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001183 goto next;
1184 }
1185
1186 if (!(child = fork())) {
1187 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001188 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001189 _exit(1);
1190 }
1191
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001192 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001193
1194 std::string storageSource;
1195 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001196 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001197 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001198 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001199 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001200 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001201 } else {
1202 // Sane default of no storage visible
1203 _exit(0);
1204 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001205 if (TEMP_FAILURE_RETRY(
1206 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1207 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001208 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001209 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001210 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1211 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001212 _exit(1);
1213 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001214
1215 // Mount user-specific symlink helper into place
1216 userid_t user_id = multiuser_get_user_id(uid);
1217 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001218 if (TEMP_FAILURE_RETRY(
1219 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1220 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001221 _exit(1);
1222 }
1223
Jeff Sharkey66270a22015-06-24 11:49:24 -07001224 _exit(0);
1225 }
1226
1227 if (child == -1) {
1228 PLOG(ERROR) << "Failed to fork";
1229 goto next;
1230 } else {
1231 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1232 }
1233
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001234 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001235 close(nsFd);
1236 close(pidFd);
1237 }
1238 closedir(dir);
1239 return 0;
1240}
1241
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001242int VolumeManager::reset() {
1243 // Tear down all existing disks/volumes and start from a blank slate so
1244 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001245 if (mInternalEmulated != nullptr) {
1246 mInternalEmulated->destroy();
1247 mInternalEmulated->create();
1248 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001249 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001250 disk->destroy();
1251 disk->create();
1252 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001253 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001254 mAddedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001255
1256 mUserPackages.clear();
1257 mAppIds.clear();
1258 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001259 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001260
Sudheer Shanka023b5392019-02-06 12:39:19 -08001261 for (userid_t userId : mStartedUsers) {
1262 DeleteDirContentsAndDir(StringPrintf("/mnt/user/%d/package", userId));
1263 }
1264 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001265 return 0;
1266}
1267
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001268// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001269int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001270 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001271 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001272 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001273 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001274 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001275 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001276 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001277 disk->destroy();
1278 }
Risan8c9f3322018-10-29 08:52:56 +09001279 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001280 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001281 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001282 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001283 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001284}
1285
Jeff Sharkey9c484982015-03-31 10:35:33 -07001286int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001287 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001288 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001289
Jeff Sharkey9c484982015-03-31 10:35:33 -07001290 // First, try gracefully unmounting all known devices
1291 if (mInternalEmulated != nullptr) {
1292 mInternalEmulated->unmount();
1293 }
Risan8c9f3322018-10-29 08:52:56 +09001294 for (const auto& stub : mStubVolumes) {
1295 stub->unmount();
1296 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001297 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001298 disk->unmountAll();
1299 }
1300
1301 // Worst case we might have some stale mounts lurking around, so
1302 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001303 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001304 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001305 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001306 return -errno;
1307 }
1308
1309 // Some volumes can be stacked on each other, so force unmount in
1310 // reverse order to give us the best chance of success.
1311 std::list<std::string> toUnmount;
1312 mntent* mentry;
1313 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001314 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001315 if ((StartsWith(test, "/mnt/") &&
1316#ifdef __ANDROID_DEBUGGABLE__
1317 !StartsWith(test, "/mnt/scratch") &&
1318#endif
1319 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1320 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001321 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001322 }
1323 }
1324 endmntent(fp);
1325
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001326 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001327 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001328 android::vold::ForceUnmount(path);
1329 }
1330
1331 return 0;
1332}
1333
Jeff Sharkey3472e522017-10-06 18:02:53 -06001334int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001335 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001336 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001337 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001338 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001339 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001340 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001341 return -EINVAL;
1342 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001343}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001344
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001345int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001346 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001347 int id = mNextObbId++;
1348
1349 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001350 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001351 vol->create();
1352
1353 mObbVolumes.push_back(vol);
1354 *outVolId = vol->getId();
1355 return android::OK;
1356}
1357
1358int VolumeManager::destroyObb(const std::string& volId) {
1359 auto i = mObbVolumes.begin();
1360 while (i != mObbVolumes.end()) {
1361 if ((*i)->getId() == volId) {
1362 (*i)->destroy();
1363 i = mObbVolumes.erase(i);
1364 } else {
1365 ++i;
1366 }
1367 }
1368 return android::OK;
1369}
1370
Risan8c9f3322018-10-29 08:52:56 +09001371int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1372 const std::string& fsType, const std::string& fsUuid,
1373 const std::string& fsLabel, std::string* outVolId) {
1374 int id = mNextStubVolumeId++;
1375 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1376 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1377 vol->create();
1378
1379 mStubVolumes.push_back(vol);
1380 *outVolId = vol->getId();
1381 return android::OK;
1382}
1383
1384int VolumeManager::destroyStubVolume(const std::string& volId) {
1385 auto i = mStubVolumes.begin();
1386 while (i != mStubVolumes.end()) {
1387 if ((*i)->getId() == volId) {
1388 (*i)->destroy();
1389 i = mStubVolumes.erase(i);
1390 } else {
1391 ++i;
1392 }
1393 }
1394 return android::OK;
1395}
1396
Risan8f6198d2018-10-26 20:56:45 -06001397int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001398 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001399}
1400
Risan8f6198d2018-10-26 20:56:45 -06001401int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001402 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001403}
1404
1405int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001406 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001407}