blob: fad59f1ed56a7c2acde10b79a3d10640b8ac552b [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080022#include <mntent.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080028#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070029#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070030#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070033#include <array>
San Mehata19b2502010-01-06 10:33:53 -080034
San Mehata2677e42009-12-13 10:40:18 -080035#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070036
Jiyong Park8d21c922019-01-04 13:35:25 +090037#include <ApexProperties.sysprop.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080038#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070039#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060040#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080041#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070042#include <android-base/strings.h>
43
Jeff Sharkey71ebe152013-09-17 17:24:38 -070044#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060045#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070046
Robert Craigb9e3ba52014-02-04 10:53:00 -050047#include <selinux/android.h>
48
San Mehatfd7f5872009-10-12 11:32:47 -070049#include <sysutils/NetlinkEvent.h>
50
Kenny Root344ca102012-04-03 17:23:01 -070051#include <private/android_filesystem_config.h>
52
Eric Biggersa701c452018-10-23 13:06:55 -070053#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070054
Risanac02a482018-10-31 21:59:47 -060055#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070056#include "Devmapper.h"
Eric Biggersa701c452018-10-23 13:06:55 -070057#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080058#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070059#include "NetlinkManager.h"
60#include "Process.h"
61#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070062#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070063#include "VoldUtil.h"
64#include "VolumeManager.h"
65#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070066#include "fs/Ext4.h"
67#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070068#include "model/EmulatedVolume.h"
69#include "model/ObbVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090070#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080071
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000072using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070073using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070074using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070075using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070076using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060077using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080078using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000079using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080080using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080081using android::vold::DeleteDirContentsAndDir;
82using android::vold::Symlink;
83using android::vold::Unlink;
84using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080085using android::vold::VoldNativeService;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070086
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060087static const char* kPathUserMount = "/mnt/user";
88static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
89
Sudheer Shanka53947a32018-08-01 10:24:13 -070090static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Sudheer Shanka34b437b2019-01-17 17:20:47 -080091static const char* kIsolatedStorageSnapshot = "sys.isolated_storage_snapshot";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060092static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
93
Sudheer Shanka53947a32018-08-01 10:24:13 -070094static const std::string kEmptyString("");
95
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060096/* 512MiB is large enough for testing purposes */
97static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070098
Jeff Sharkey36801cc2015-03-13 16:09:20 -070099static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +0800100static const unsigned int kMajorBlockExperimentalMin = 240;
101static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700102
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700103VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700104
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700105VolumeManager* VolumeManager::Instance() {
106 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700107 return sInstance;
108}
109
110VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800111 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600112 mNextObbId = 0;
Risan8c9f3322018-10-29 08:52:56 +0900113 mNextStubVolumeId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700114 // For security reasons, assume that a secure keyguard is
115 // showing until we hear otherwise
116 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700117}
118
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700119VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800120
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800121static bool hasIsolatedStorage() {
Jeff Sharkeya6082502019-02-11 12:18:48 -0700122 return GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, true));
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800123}
124
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600125int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600126 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700127 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600128 if (access(kPathVirtualDisk, F_OK) != 0) {
129 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
130 }
131
132 if (mVirtualDisk == nullptr) {
133 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
134 LOG(ERROR) << "Failed to create virtual disk";
135 return -1;
136 }
137
138 struct stat buf;
139 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
140 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
141 return -1;
142 }
143
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700144 auto disk = new android::vold::Disk(
145 "virtual", buf.st_rdev, "virtual",
146 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600147 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700148 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600149 }
150 } else {
151 if (mVirtualDisk != nullptr) {
152 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700153 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600154
155 Loop::destroyByDevice(mVirtualDiskPath.c_str());
156 mVirtualDisk = nullptr;
157 }
158
159 if (access(kPathVirtualDisk, F_OK) == 0) {
160 unlink(kPathVirtualDisk);
161 }
162 }
163 return 0;
164}
165
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700166int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800167 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700168 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800169}
170
San Mehatf1b736b2009-10-10 17:22:08 -0700171int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600172 ATRACE_NAME("VolumeManager::start");
173
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700174 // Always start from a clean slate by unmounting everything in
175 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700176 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600178 Devmapper::destroyAll();
179 Loop::destroyAll();
180
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700181 // Assume that we always have an emulated volume on internal
182 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700183 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700184 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700185 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700186 mInternalEmulated->create();
187
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600188 // Consider creating a virtual disk
189 updateVirtualDisk();
190
San Mehatf1b736b2009-10-10 17:22:08 -0700191 return 0;
192}
193
194int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700195 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700196 mInternalEmulated->destroy();
197 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700198 return 0;
199}
200
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700201void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700202 std::lock_guard<std::mutex> lock(mLock);
203
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700204 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700205 LOG(DEBUG) << "----------------";
206 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700207 evt->dump();
208 }
San Mehatf1b736b2009-10-10 17:22:08 -0700209
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700210 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
211 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700212
213 if (devType != "disk") return;
214
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600215 int major = std::stoi(evt->findParam("MAJOR"));
216 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700217 dev_t device = makedev(major, minor);
218
219 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700220 case NetlinkEvent::Action::kAdd: {
221 for (const auto& source : mDiskSources) {
222 if (source->matches(eventPath)) {
223 // For now, assume that MMC and virtio-blk (the latter is
224 // emulator-specific; see Disk.cpp for details) devices are SD,
225 // and that everything else is USB
226 int flags = source->getFlags();
227 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
228 major >= (int)kMajorBlockExperimentalMin &&
229 major <= (int)kMajorBlockExperimentalMax)) {
230 flags |= android::vold::Disk::Flags::kSd;
231 } else {
232 flags |= android::vold::Disk::Flags::kUsb;
233 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700234
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700235 auto disk =
236 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
237 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
238 break;
239 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700240 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700241 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700242 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700243 case NetlinkEvent::Action::kChange: {
244 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
245 handleDiskChanged(device);
246 break;
247 }
248 case NetlinkEvent::Action::kRemove: {
249 handleDiskRemoved(device);
250 break;
251 }
252 default: {
253 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
254 break;
255 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700256 }
257}
258
Jeff Sharkey401b2602017-12-14 22:15:20 -0700259void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
260 // For security reasons, if secure keyguard is showing, wait
261 // until the user unlocks the device to actually touch it
262 if (mSecureKeyguardShowing) {
263 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700264 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700265 mPendingDisks.push_back(disk);
266 } else {
267 disk->create();
268 mDisks.push_back(disk);
269 }
270}
271
272void VolumeManager::handleDiskChanged(dev_t device) {
273 for (const auto& disk : mDisks) {
274 if (disk->getDevice() == device) {
275 disk->readMetadata();
276 disk->readPartitions();
277 }
278 }
279
280 // For security reasons, we ignore all pending disks, since
281 // we'll scan them once the device is unlocked
282}
283
284void VolumeManager::handleDiskRemoved(dev_t device) {
285 auto i = mDisks.begin();
286 while (i != mDisks.end()) {
287 if ((*i)->getDevice() == device) {
288 (*i)->destroy();
289 i = mDisks.erase(i);
290 } else {
291 ++i;
292 }
293 }
294 auto j = mPendingDisks.begin();
295 while (j != mPendingDisks.end()) {
296 if ((*j)->getDevice() == device) {
297 j = mPendingDisks.erase(j);
298 } else {
299 ++j;
300 }
301 }
302}
303
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700304void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800305 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700306 mDiskSources.push_back(diskSource);
307}
308
309std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
310 for (auto disk : mDisks) {
311 if (disk->getId() == id) {
312 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700313 }
314 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700315 return nullptr;
316}
San Mehatf1b736b2009-10-10 17:22:08 -0700317
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800319 // Vold could receive "mount" after "shutdown" command in the extreme case.
320 // If this happens, mInternalEmulated will equal nullptr and
321 // we need to deal with it in order to avoid null pointer crash.
322 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700323 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700324 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700325 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700326 auto vol = disk->findVolume(id);
327 if (vol != nullptr) {
328 return vol;
329 }
330 }
Risan8c9f3322018-10-29 08:52:56 +0900331 for (const auto& vol : mStubVolumes) {
332 if (vol->getId() == id) {
333 return vol;
334 }
335 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600336 for (const auto& vol : mObbVolumes) {
337 if (vol->getId() == id) {
338 return vol;
339 }
340 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700341 return nullptr;
342}
343
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800344void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
345 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700346 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700347 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700348 disk->listVolumes(type, list);
349 }
350}
351
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600352int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700353 std::string normalizedGuid;
354 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
355 LOG(WARNING) << "Invalid GUID " << partGuid;
356 return -1;
357 }
358
Paul Crowleyc6433a22017-10-24 14:54:43 -0700359 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700360 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
361 if (unlink(keyPath.c_str()) != 0) {
362 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700363 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700364 }
Eric Biggersa701c452018-10-23 13:06:55 -0700365 if (fscrypt_is_native()) {
366 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700367 success = false;
368 }
369 }
370 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700371}
372
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700373int VolumeManager::linkPrimary(userid_t userId) {
374 std::string source(mPrimary->getPath());
375 if (mPrimary->isEmulated()) {
376 source = StringPrintf("%s/%d", source.c_str(), userId);
377 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
378 }
379
380 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700381 LOG(DEBUG) << "Linking " << source << " to " << target;
Sudheer Shanka023b5392019-02-06 12:39:19 -0800382 Symlink(source, target);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700383 return 0;
384}
385
386int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
387 const std::string& mntTargetRoot,
388 const std::string& packageName, const char* dirName) {
389 std::string mntSourceDir =
390 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000391 if (CreateDir(mntSourceDir, 0755) < 0) {
392 return -errno;
393 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700394 std::string mntTargetDir =
395 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000396 if (CreateDir(mntTargetDir, 0755) < 0) {
397 return -errno;
398 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800399 return BindMount(mntSourceDir, mntTargetDir);
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700400}
401
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700402int VolumeManager::mountPkgSpecificDirsForRunningProcs(
403 userid_t userId, const std::vector<std::string>& packageNames,
Sudheer Shanka817b9112018-12-13 17:40:28 -0800404 const std::vector<std::string>& visibleVolLabels, int remountMode) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700405 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
406 if (!dirp) {
407 PLOG(ERROR) << "Failed to opendir /proc";
408 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700409 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700410
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700411 std::string rootName;
412 // Figure out root namespace to compare against below
413 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
414 PLOG(ERROR) << "Failed to read root namespace";
415 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700416 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700417
Sudheer Shanka55049012019-01-09 12:15:15 -0800418 struct stat mntFullSb;
419 struct stat mntWriteSb;
420 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/full", &mntFullSb)) == -1) {
421 PLOG(ERROR) << "Failed to stat /mnt/runtime/full";
422 return -1;
423 }
424 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &mntWriteSb)) == -1) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700425 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
426 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700427 }
428
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800429 std::string obbMountDir = StringPrintf("/mnt/user/%d/obb_mount", userId);
430 if (fs_prepare_dir(obbMountDir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
431 PLOG(ERROR) << "Failed to fs_prepare_dir " << obbMountDir;
432 return -1;
433 }
434 const unique_fd obbMountDirFd(
435 TEMP_FAILURE_RETRY(open(obbMountDir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)));
436 if (obbMountDirFd.get() < 0) {
437 PLOG(ERROR) << "Failed to open " << obbMountDir;
438 return -1;
439 }
440
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700441 std::unordered_set<appid_t> validAppIds;
442 for (auto& package : packageNames) {
443 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700444 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700445 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700446
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800447 std::vector<pid_t> childPids;
448
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700449 struct dirent* de;
450 // Poke through all running PIDs look for apps running in userId
451 while ((de = readdir(dirp.get()))) {
452 pid_t pid;
453 if (de->d_type != DT_DIR) continue;
454 if (!android::base::ParseInt(de->d_name, &pid)) continue;
455
456 const unique_fd pidFd(
457 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
458 if (pidFd.get() < 0) {
459 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700460 continue;
461 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700462 struct stat sb;
463 if (fstat(pidFd.get(), &sb) != 0) {
464 PLOG(WARNING) << "Failed to stat " << de->d_name;
465 continue;
466 }
467 if (multiuser_get_user_id(sb.st_uid) != userId) {
468 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700469 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700470
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700471 // Matches so far, but refuse to touch if in root namespace
472 LOG(VERBOSE) << "Found matching PID " << de->d_name;
473 std::string pidName;
474 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
475 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
476 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700477 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700478 if (rootName == pidName) {
479 LOG(WARNING) << "Skipping due to root namespace";
480 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700481 }
482
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700483 // Only update the mount points of processes running with one of validAppIds.
484 // This should skip any isolated uids.
485 appid_t appId = multiuser_get_app_id(sb.st_uid);
486 if (validAppIds.find(appId) == validAppIds.end()) {
487 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700488 }
489
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700490 std::vector<std::string> packagesForUid;
491 for (auto& package : userPackages) {
492 if (mAppIds[package] == appId) {
493 packagesForUid.push_back(package);
494 }
495 }
496 if (packagesForUid.empty()) {
497 continue;
498 }
499 const std::string& sandboxId = mSandboxIds[appId];
500
501 // We purposefully leave the namespace open across the fork
Nick Kralevich58e1a812019-03-29 18:35:22 -0700502 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
503 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY));
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700504 if (nsFd.get() < 0) {
505 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
506 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700507 }
508
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700509 pid_t child;
510 if (!(child = fork())) {
511 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
512 PLOG(ERROR) << "Failed to setns for " << de->d_name;
513 _exit(1);
514 }
515
Sudheer Shanka817b9112018-12-13 17:40:28 -0800516 int mountMode;
517 if (remountMode == -1) {
Sudheer Shanka55049012019-01-09 12:15:15 -0800518 mountMode =
519 getMountModeForRunningProc(packagesForUid, userId, mntWriteSb, mntFullSb);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800520 if (mountMode == -1) {
521 _exit(1);
522 }
523 } else {
524 mountMode = remountMode;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800525 if (handleMountModeInstaller(mountMode, obbMountDirFd.get(), obbMountDir,
526 sandboxId) < 0) {
527 _exit(1);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800528 }
529 }
530 if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
Sudheer Shanka55049012019-01-09 12:15:15 -0800531 mountMode == VoldNativeService::REMOUNT_MODE_LEGACY ||
Sudheer Shanka817b9112018-12-13 17:40:28 -0800532 mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
533 // These mount modes are not going to change dynamically, so don't bother
534 // unmounting/remounting dirs.
535 _exit(0);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700536 }
537
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700538 for (auto& volumeLabel : visibleVolLabels) {
539 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
540 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
541 if (volumeLabel == "emulated") {
542 StringAppendF(&mntSource, "/%d", userId);
543 StringAppendF(&mntTarget, "/%d", userId);
544 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800545
546 std::string sandboxSource =
547 StringPrintf("%s/Android/sandbox/%s", mntSource.c_str(), sandboxId.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000548 if (CreateDir(sandboxSource, 0755) < 0) {
549 continue;
550 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800551 if (BindMount(sandboxSource, mntTarget) < 0) {
552 continue;
553 }
554
Sudheer Shanka817b9112018-12-13 17:40:28 -0800555 std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
556 std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
Sudheer Shanka023b5392019-02-06 12:39:19 -0800557 if (UnmountTree(obbTargetDir) < 0) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800558 continue;
559 }
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000560 if (!createPkgSpecificDirRoots(mntSource) || !createPkgSpecificDirRoots(mntTarget)) {
561 continue;
562 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700563 for (auto& package : packagesForUid) {
564 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
565 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
Sudheer Shanka03992e32018-12-12 12:43:38 -0800566 if (mountMode != VoldNativeService::REMOUNT_MODE_INSTALLER) {
567 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
568 }
569 }
570 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800571 if (BindMount(obbSourceDir, obbTargetDir) < 0) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800572 continue;
573 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700574 }
575 }
576 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700577 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700578
579 if (child == -1) {
580 PLOG(ERROR) << "Failed to fork";
581 } else {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800582 childPids.push_back(child);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700583 }
584 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800585 for (auto& child : childPids) {
586 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
587 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700588 return 0;
589}
590
Sudheer Shanka03992e32018-12-12 12:43:38 -0800591int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
Sudheer Shanka55049012019-01-09 12:15:15 -0800592 userid_t userId, struct stat& mntWriteStat,
593 struct stat& mntFullStat) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800594 struct stat storageSb;
595 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
596 PLOG(ERROR) << "Failed to stat /storage";
597 return -1;
598 }
599
600 // Some packages have access to full external storage, identify processes belonging
Sudheer Shanka55049012019-01-09 12:15:15 -0800601 // to those packages by comparing inode no.s of /mnt/runtime/full and /storage
602 if (storageSb.st_dev == mntFullStat.st_dev && storageSb.st_ino == mntFullStat.st_ino) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800603 return VoldNativeService::REMOUNT_MODE_FULL;
Sudheer Shanka55049012019-01-09 12:15:15 -0800604 } else if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
605 return VoldNativeService::REMOUNT_MODE_LEGACY;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800606 }
607
608 std::string obbMountFile =
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800609 StringPrintf("/mnt/user/%d/obb_mount/%s", userId, packagesForUid[0].c_str());
610 if (TEMP_FAILURE_RETRY(access(obbMountFile.c_str(), F_OK)) != -1) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800611 return VoldNativeService::REMOUNT_MODE_INSTALLER;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800612 } else if (errno != ENOENT) {
613 PLOG(ERROR) << "Failed to access " << obbMountFile;
614 return -1;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800615 }
616
617 // Some packages don't have access to external storage and processes belonging to
618 // those packages don't have anything mounted at /storage. So, identify those
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800619 // processes by comparing inode no.s of /mnt/user/%d/package
Sudheer Shanka03992e32018-12-12 12:43:38 -0800620 // and /storage
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800621 std::string sandbox = StringPrintf("/mnt/user/%d/package", userId);
622 struct stat sandboxStat;
623 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
624 PLOG(ERROR) << "Failed to stat " << sandbox;
625 return -1;
626 }
627 if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
628 return VoldNativeService::REMOUNT_MODE_WRITE;
629 }
630
631 return VoldNativeService::REMOUNT_MODE_NONE;
632}
633
634int VolumeManager::handleMountModeInstaller(int mountMode, int obbMountDirFd,
635 const std::string& obbMountDir,
636 const std::string& sandboxId) {
637 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
638 if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
639 return 0;
640 } else if (errno != ENOENT) {
641 PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
642 return -errno;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800643 }
Nick Kralevich58e1a812019-03-29 18:35:22 -0700644 const unique_fd fd(TEMP_FAILURE_RETRY(
645 openat(obbMountDirFd, sandboxId.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800646 if (fd.get() < 0) {
647 PLOG(ERROR) << "Failed to create " << obbMountDir << "/" << sandboxId;
648 return -errno;
649 }
650 } else {
651 if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
652 if (TEMP_FAILURE_RETRY(unlinkat(obbMountDirFd, sandboxId.c_str(), 0)) == -1) {
653 PLOG(ERROR) << "Failed to unlink " << obbMountDir << "/" << sandboxId;
654 return -errno;
655 }
656 } else if (errno != ENOENT) {
657 PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
658 return -errno;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800659 }
660 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800661 return 0;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800662}
663
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700664int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
665 const std::vector<std::string>& visibleVolLabels) {
666 if (visibleVolLabels.empty()) {
667 return 0;
668 }
669 for (auto& volumeLabel : visibleVolLabels) {
670 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
671 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
672 if (isVolPrimaryEmulated) {
673 StringAppendF(&volumeRoot, "/%d", userId);
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000674 if (CreateDir(volumeRoot, 0755) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700675 return -errno;
676 }
677 }
678
679 std::string sandboxRoot =
680 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
681 if (sandboxRoot.empty()) {
682 return -errno;
683 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700684 }
Sudheer Shanka83680402019-02-24 10:16:09 -0800685
686 if (prepareSandboxTargets(userId, visibleVolLabels) < 0) {
687 return -errno;
688 }
689
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800690 if (mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1) < 0) {
691 PLOG(ERROR) << "Failed to setup sandboxes for already running processes";
692 return -errno;
693 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700694 return 0;
695}
696
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000697int VolumeManager::prepareSandboxTargets(userid_t userId,
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000698 const std::vector<std::string>& visibleVolLabels) {
699 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
700 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800701 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000702 return -errno;
703 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800704
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000705 StringAppendF(&mntTargetRoot, "/package");
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800706 if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
707 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000708 return -errno;
709 }
710
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800711 for (auto& volumeLabel : visibleVolLabels) {
712 std::string sandboxTarget =
713 StringPrintf("%s/%s", mntTargetRoot.c_str(), volumeLabel.c_str());
714 if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
715 PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
716 return -errno;
717 }
718
719 if (mPrimary && volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
720 StringAppendF(&sandboxTarget, "/%d", userId);
721 if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
722 PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
723 return -errno;
724 }
725 }
726 }
727
728 StringAppendF(&mntTargetRoot, "/self");
729 if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
730 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000731 return -errno;
732 }
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000733
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000734 if (mPrimary) {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800735 std::string pkgPrimarySource(mPrimary->getPath());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000736 if (mPrimary->isEmulated()) {
737 StringAppendF(&pkgPrimarySource, "/%d", userId);
738 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800739 StringAppendF(&mntTargetRoot, "/primary");
740 if (Symlink(pkgPrimarySource, mntTargetRoot) < 0) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000741 return -errno;
742 }
743 }
744 return 0;
745}
746
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700747std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
748 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700749 std::string path(pathPrefix);
750 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
751 for (size_t i = 0; i < subDirList.size(); ++i) {
752 std::string subDir = subDirList[i];
753 if (subDir.empty()) {
754 continue;
755 }
756 StringAppendF(&path, "/%s", subDir.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000757 if (CreateDir(path, mode) < 0) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700758 return kEmptyString;
759 }
760 }
761 return path;
762}
763
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700764bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
765 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000766 if (CreateDir(volumeAndroidRoot, 0700) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700767 return false;
768 }
769 std::array<std::string, 3> dirs = {"data", "media", "obb"};
770 for (auto& dir : dirs) {
771 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000772 if (CreateDir(path, 0700) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700773 return false;
774 }
775 }
776 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700777}
778
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700779int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
780 mAddedUsers[userId] = userSerialNumber;
781 return 0;
782}
783
784int VolumeManager::onUserRemoved(userid_t userId) {
785 mAddedUsers.erase(userId);
786 return 0;
787}
788
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700789int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
790 const std::vector<int>& appIds,
791 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700792 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700793 // Note that sometimes the system will spin up processes from Zygote
794 // before actually starting the user, so we're okay if Zygote
795 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600796 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700797 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
798
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700799 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700800 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700801 for (size_t i = 0; i < packageNames.size(); ++i) {
802 mAppIds[packageNames[i]] = appIds[i];
803 mSandboxIds[appIds[i]] = sandboxIds[i];
804 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700805 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700806 linkPrimary(userId);
807 }
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800808 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700809 std::vector<std::string> visibleVolLabels;
810 for (auto& volId : mVisibleVolumeIds) {
811 auto vol = findVolume(volId);
812 userid_t mountUserId = vol->getMountUserId();
813 if (mountUserId == userId || vol->isEmulated()) {
814 visibleVolLabels.push_back(vol->getLabel());
815 }
816 }
817 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
818 return -errno;
819 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700820 }
821 return 0;
822}
823
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700824int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700825 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700826 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700827
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800828 if (hasIsolatedStorage()) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800829 auto& userPackages = mUserPackages[userId];
830 std::string userMntTargetRoot = StringPrintf("/mnt/user/%d", userId);
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800831 std::string pkgPrimaryDir =
832 StringPrintf("%s/package/self/primary", userMntTargetRoot.c_str());
833 if (Unlink(pkgPrimaryDir) < 0) {
834 return -errno;
Sudheer Shanka023b5392019-02-06 12:39:19 -0800835 }
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700836 mUserPackages.erase(userId);
Sudheer Shanka023b5392019-02-06 12:39:19 -0800837 if (DeleteDirContentsAndDir(userMntTargetRoot) < 0) {
838 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << userMntTargetRoot;
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700839 return -errno;
840 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800841 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << userMntTargetRoot;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700842 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700843 return 0;
844}
845
Sudheer Shankad484aa92018-07-31 10:07:34 -0700846int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700847 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700848 for (size_t i = 0; i < packageNames.size(); ++i) {
849 mAppIds[packageNames[i]] = appIds[i];
850 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700851 return 0;
852}
853
854int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700855 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700856 for (size_t i = 0; i < appIds.size(); ++i) {
857 mSandboxIds[appIds[i]] = sandboxIds[i];
858 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700859 return 0;
860}
861
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700862int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
863 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800864 if (!hasIsolatedStorage()) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700865 return 0;
866 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
867 // User not started, no need to do anything now. Required bind mounts for the package will
868 // be created when the user starts.
869 return 0;
870 }
Sudheer Shanka23d725d2019-02-28 10:46:48 -0800871
872 auto& userPackages = mUserPackages[userId];
873 if (std::find(userPackages.begin(), userPackages.end(), packageName) != userPackages.end()) {
874 return 0;
875 }
876
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700877 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700878 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700879 mUserPackages[userId].push_back(packageName);
880 mAppIds[packageName] = appId;
881 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700882
883 std::vector<std::string> visibleVolLabels;
884 for (auto& volId : mVisibleVolumeIds) {
885 auto vol = findVolume(volId);
886 userid_t mountUserId = vol->getMountUserId();
887 if (mountUserId == userId || vol->isEmulated()) {
888 visibleVolLabels.push_back(vol->getLabel());
889 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700890 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700891 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700892}
893
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700894int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700895 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800896 if (!hasIsolatedStorage()) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700897 return 0;
898 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700899 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
900 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700901 auto& userPackages = mUserPackages[userId];
Sudheer Shankaba0c62f2018-12-16 18:22:34 -0800902 userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
903 userPackages.end());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700904 // If the package is not uninstalled in any other users, remove appId and sandboxId
905 // corresponding to it from the internal state.
906 bool installedInAnyUser = false;
907 for (auto& it : mUserPackages) {
908 auto& packages = it.second;
909 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
910 installedInAnyUser = true;
911 break;
912 }
913 }
914 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700915 const auto& entry = mAppIds.find(packageName);
916 if (entry != mAppIds.end()) {
917 mSandboxIds.erase(entry->second);
918 mAppIds.erase(entry);
919 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700920 }
921
922 std::vector<std::string> visibleVolLabels;
923 for (auto& volId : mVisibleVolumeIds) {
924 auto vol = findVolume(volId);
925 userid_t mountUserId = vol->getMountUserId();
926 if (mountUserId == userId || vol->isEmulated()) {
927 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
928 return -errno;
929 }
930 }
931 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800932
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700933 return 0;
934}
935
936int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
937 const std::string& sandboxId, userid_t userId,
938 const std::string& volLabel) {
939 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
940 << ", volLabel=" << volLabel;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700941
942 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
943 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
944 StringAppendF(&sandboxDir, "/%d", userId);
945 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700946 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700947
Sudheer Shanka023b5392019-02-06 12:39:19 -0800948 if (DeleteDirContentsAndDir(sandboxDir) < 0) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700949 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
950 return -errno;
951 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800952
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700953 return 0;
954}
955
Jeff Sharkey401b2602017-12-14 22:15:20 -0700956int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
957 mSecureKeyguardShowing = isShowing;
958 if (!mSecureKeyguardShowing) {
959 // Now that secure keyguard has been dismissed, process
960 // any pending disks
961 for (const auto& disk : mPendingDisks) {
962 disk->create();
963 mDisks.push_back(disk);
964 }
965 mPendingDisks.clear();
966 }
967 return 0;
968}
969
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700970int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800971 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700972 return 0;
973 }
974
975 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
976 return 0;
977 }
978
979 mVisibleVolumeIds.insert(vol->getId());
980 userid_t mountUserId = vol->getMountUserId();
981 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
982 // We don't want to create another shared_ptr here because then we will end up with
983 // two shared_ptrs owning the underlying pointer without sharing it.
984 mPrimary = findVolume(vol->getId());
985 for (userid_t userId : mStartedUsers) {
986 if (linkPrimary(userId) != 0) {
987 return -errno;
988 }
989 }
990 }
991 if (vol->isEmulated()) {
992 for (userid_t userId : mStartedUsers) {
993 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
994 return -errno;
995 }
996 }
997 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
998 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
999 return -errno;
1000 }
1001 }
1002 return 0;
1003}
1004
1005int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001006 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001007 return 0;
1008 }
1009
1010 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
1011 return 0;
1012 }
1013
1014 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1015 mPrimary = nullptr;
1016 }
1017
1018 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
1019 userid_t mountUserId = vol->getMountUserId();
1020 if (vol->isEmulated()) {
1021 for (userid_t userId : mStartedUsers) {
1022 if (destroySandboxesForVol(vol, userId) != 0) {
1023 return -errno;
1024 }
1025 }
1026 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1027 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1028 return -errno;
1029 }
1030 }
1031 return 0;
1032}
1033
1034int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1035 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -08001036 std::string volSandboxRoot =
1037 StringPrintf("/mnt/user/%d/package/%s", userId, vol->getLabel().c_str());
1038 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1039 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1040 return -errno;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001041 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -08001042 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001043 return 0;
1044}
1045
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001046int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001047 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001048 return 0;
1049 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001050 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001051 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001052 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001053 }
1054 return 0;
1055}
1056
Sudheer Shanka817b9112018-12-13 17:40:28 -08001057int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001058 if (!hasIsolatedStorage()) {
Sudheer Shanka817b9112018-12-13 17:40:28 -08001059 return remountUidLegacy(uid, mountMode);
1060 }
1061
1062 appid_t appId = multiuser_get_app_id(uid);
1063 userid_t userId = multiuser_get_user_id(uid);
1064 std::vector<std::string> visibleVolLabels;
1065 for (auto& volId : mVisibleVolumeIds) {
1066 auto vol = findVolume(volId);
1067 userid_t mountUserId = vol->getMountUserId();
1068 if (mountUserId == userId || vol->isEmulated()) {
1069 visibleVolLabels.push_back(vol->getLabel());
1070 }
1071 }
1072
1073 // Finding one package with appId is enough
1074 std::vector<std::string> packageNames;
1075 for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
1076 if (it->second == appId) {
1077 packageNames.push_back(it->first);
1078 break;
1079 }
1080 }
1081 if (packageNames.empty()) {
1082 PLOG(ERROR) << "Failed to find packageName for " << uid;
Sudheer Shanka53947a32018-08-01 10:24:13 -07001083 return -1;
1084 }
Sudheer Shanka817b9112018-12-13 17:40:28 -08001085 return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
1086}
1087
1088int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
1089 std::string mode;
1090 switch (mountMode) {
1091 case VoldNativeService::REMOUNT_MODE_NONE:
1092 mode = "none";
1093 break;
1094 case VoldNativeService::REMOUNT_MODE_DEFAULT:
1095 mode = "default";
1096 break;
1097 case VoldNativeService::REMOUNT_MODE_READ:
1098 mode = "read";
1099 break;
1100 case VoldNativeService::REMOUNT_MODE_WRITE:
1101 mode = "write";
1102 break;
1103 default:
1104 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
1105 return -1;
1106 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001107 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1108
1109 DIR* dir;
1110 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001111 std::string rootName;
1112 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001113 int pidFd;
1114 int nsFd;
1115 struct stat sb;
1116 pid_t child;
1117
Jiyong Park8d21c922019-01-04 13:35:25 +09001118 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
1119
Jeff Sharkey66270a22015-06-24 11:49:24 -07001120 if (!(dir = opendir("/proc"))) {
1121 PLOG(ERROR) << "Failed to opendir";
1122 return -1;
1123 }
1124
1125 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001126 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1127 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001128 closedir(dir);
1129 return -1;
1130 }
1131
1132 // Poke through all running PIDs look for apps running as UID
1133 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001134 pid_t pid;
1135 if (de->d_type != DT_DIR) continue;
1136 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1137
Jeff Sharkey66270a22015-06-24 11:49:24 -07001138 pidFd = -1;
1139 nsFd = -1;
1140
1141 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1142 if (pidFd < 0) {
1143 goto next;
1144 }
1145 if (fstat(pidFd, &sb) != 0) {
1146 PLOG(WARNING) << "Failed to stat " << de->d_name;
1147 goto next;
1148 }
1149 if (sb.st_uid != uid) {
1150 goto next;
1151 }
1152
1153 // Matches so far, but refuse to touch if in root namespace
1154 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001155 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001156 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1157 goto next;
1158 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001159 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001160 LOG(WARNING) << "Skipping due to root namespace";
1161 goto next;
1162 }
1163
Jiyong Park8d21c922019-01-04 13:35:25 +09001164 if (apexUpdatable) {
1165 std::string exeName;
1166 // When ro.apex.bionic_updatable is set to true,
1167 // some early native processes have mount namespaces that are different
1168 // from that of the init. Therefore, above check can't filter them out.
1169 // Since the propagation type of / is 'shared', unmounting /storage
1170 // for the early native processes affects other processes including
1171 // init. Filter out such processes by skipping if a process is a
1172 // non-Java process whose UID is < AID_APP_START. (The UID condition
1173 // is required to not filter out child processes spawned by apps.)
1174 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
1175 PLOG(WARNING) << "Failed to read exe name for " << de->d_name;
1176 goto next;
1177 }
1178 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
1179 LOG(WARNING) << "Skipping due to native system process";
1180 goto next;
1181 }
1182 }
1183
Jeff Sharkey66270a22015-06-24 11:49:24 -07001184 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -07001185 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
1186 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001187 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001188 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001189 goto next;
1190 }
1191
1192 if (!(child = fork())) {
1193 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001194 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001195 _exit(1);
1196 }
1197
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001198 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001199
1200 std::string storageSource;
1201 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001202 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001203 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001204 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001205 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001206 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001207 } else {
1208 // Sane default of no storage visible
1209 _exit(0);
1210 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001211 if (TEMP_FAILURE_RETRY(
1212 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1213 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001214 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001215 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001216 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1217 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001218 _exit(1);
1219 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001220
1221 // Mount user-specific symlink helper into place
1222 userid_t user_id = multiuser_get_user_id(uid);
1223 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001224 if (TEMP_FAILURE_RETRY(
1225 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1226 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001227 _exit(1);
1228 }
1229
Jeff Sharkey66270a22015-06-24 11:49:24 -07001230 _exit(0);
1231 }
1232
1233 if (child == -1) {
1234 PLOG(ERROR) << "Failed to fork";
1235 goto next;
1236 } else {
1237 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1238 }
1239
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001240 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001241 close(nsFd);
1242 close(pidFd);
1243 }
1244 closedir(dir);
1245 return 0;
1246}
1247
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001248int VolumeManager::reset() {
1249 // Tear down all existing disks/volumes and start from a blank slate so
1250 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001251 if (mInternalEmulated != nullptr) {
1252 mInternalEmulated->destroy();
1253 mInternalEmulated->create();
1254 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001255 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001256 disk->destroy();
1257 disk->create();
1258 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001259 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001260 mAddedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001261
1262 mUserPackages.clear();
1263 mAppIds.clear();
1264 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001265 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001266
Sudheer Shanka023b5392019-02-06 12:39:19 -08001267 for (userid_t userId : mStartedUsers) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001268 DeleteDirContents(StringPrintf("/mnt/user/%d/package", userId));
Sudheer Shanka023b5392019-02-06 12:39:19 -08001269 }
1270 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001271 return 0;
1272}
1273
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001274// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001275int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001276 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001277 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001278 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001279 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001280 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001281 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001282 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001283 disk->destroy();
1284 }
Risan8c9f3322018-10-29 08:52:56 +09001285 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001286 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001287 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001288 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001289 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001290}
1291
Jeff Sharkey9c484982015-03-31 10:35:33 -07001292int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001293 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001294 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001295
Jeff Sharkey9c484982015-03-31 10:35:33 -07001296 // First, try gracefully unmounting all known devices
1297 if (mInternalEmulated != nullptr) {
1298 mInternalEmulated->unmount();
1299 }
Risan8c9f3322018-10-29 08:52:56 +09001300 for (const auto& stub : mStubVolumes) {
1301 stub->unmount();
1302 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001303 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001304 disk->unmountAll();
1305 }
1306
1307 // Worst case we might have some stale mounts lurking around, so
1308 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001309 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001310 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001311 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001312 return -errno;
1313 }
1314
1315 // Some volumes can be stacked on each other, so force unmount in
1316 // reverse order to give us the best chance of success.
1317 std::list<std::string> toUnmount;
1318 mntent* mentry;
1319 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001320 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001321 if ((StartsWith(test, "/mnt/") &&
1322#ifdef __ANDROID_DEBUGGABLE__
1323 !StartsWith(test, "/mnt/scratch") &&
1324#endif
1325 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1326 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001327 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001328 }
1329 }
1330 endmntent(fp);
1331
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001332 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001333 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001334 android::vold::ForceUnmount(path);
1335 }
1336
1337 return 0;
1338}
1339
Jeff Sharkey3472e522017-10-06 18:02:53 -06001340int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001341 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001342 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001343 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001344 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001345 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001346 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001347 return -EINVAL;
1348 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001349}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001350
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001351int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001352 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001353 int id = mNextObbId++;
1354
1355 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001356 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001357 vol->create();
1358
1359 mObbVolumes.push_back(vol);
1360 *outVolId = vol->getId();
1361 return android::OK;
1362}
1363
1364int VolumeManager::destroyObb(const std::string& volId) {
1365 auto i = mObbVolumes.begin();
1366 while (i != mObbVolumes.end()) {
1367 if ((*i)->getId() == volId) {
1368 (*i)->destroy();
1369 i = mObbVolumes.erase(i);
1370 } else {
1371 ++i;
1372 }
1373 }
1374 return android::OK;
1375}
1376
Risan8c9f3322018-10-29 08:52:56 +09001377int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1378 const std::string& fsType, const std::string& fsUuid,
1379 const std::string& fsLabel, std::string* outVolId) {
1380 int id = mNextStubVolumeId++;
1381 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1382 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1383 vol->create();
1384
1385 mStubVolumes.push_back(vol);
1386 *outVolId = vol->getId();
1387 return android::OK;
1388}
1389
1390int VolumeManager::destroyStubVolume(const std::string& volId) {
1391 auto i = mStubVolumes.begin();
1392 while (i != mStubVolumes.end()) {
1393 if ((*i)->getId() == volId) {
1394 (*i)->destroy();
1395 i = mStubVolumes.erase(i);
1396 } else {
1397 ++i;
1398 }
1399 }
1400 return android::OK;
1401}
1402
Risan8f6198d2018-10-26 20:56:45 -06001403int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001404 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001405}
1406
Risan8f6198d2018-10-26 20:56:45 -06001407int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001408 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001409}
1410
1411int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001412 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001413}