blob: 2b0465efd47b5305ebac3724fd4e133089e6b9db [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
502 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
503 if (nsFd.get() < 0) {
504 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
505 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700506 }
507
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700508 pid_t child;
509 if (!(child = fork())) {
510 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
511 PLOG(ERROR) << "Failed to setns for " << de->d_name;
512 _exit(1);
513 }
514
Sudheer Shanka817b9112018-12-13 17:40:28 -0800515 int mountMode;
516 if (remountMode == -1) {
Sudheer Shanka55049012019-01-09 12:15:15 -0800517 mountMode =
518 getMountModeForRunningProc(packagesForUid, userId, mntWriteSb, mntFullSb);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800519 if (mountMode == -1) {
520 _exit(1);
521 }
522 } else {
523 mountMode = remountMode;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800524 if (handleMountModeInstaller(mountMode, obbMountDirFd.get(), obbMountDir,
525 sandboxId) < 0) {
526 _exit(1);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800527 }
528 }
529 if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
Sudheer Shanka55049012019-01-09 12:15:15 -0800530 mountMode == VoldNativeService::REMOUNT_MODE_LEGACY ||
Sudheer Shanka817b9112018-12-13 17:40:28 -0800531 mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
532 // These mount modes are not going to change dynamically, so don't bother
533 // unmounting/remounting dirs.
534 _exit(0);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700535 }
536
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700537 for (auto& volumeLabel : visibleVolLabels) {
538 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
539 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
540 if (volumeLabel == "emulated") {
541 StringAppendF(&mntSource, "/%d", userId);
542 StringAppendF(&mntTarget, "/%d", userId);
543 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800544
545 std::string sandboxSource =
546 StringPrintf("%s/Android/sandbox/%s", mntSource.c_str(), sandboxId.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000547 if (CreateDir(sandboxSource, 0755) < 0) {
548 continue;
549 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800550 if (BindMount(sandboxSource, mntTarget) < 0) {
551 continue;
552 }
553
Sudheer Shanka817b9112018-12-13 17:40:28 -0800554 std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
555 std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
Sudheer Shanka023b5392019-02-06 12:39:19 -0800556 if (UnmountTree(obbTargetDir) < 0) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800557 continue;
558 }
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000559 if (!createPkgSpecificDirRoots(mntSource) || !createPkgSpecificDirRoots(mntTarget)) {
560 continue;
561 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700562 for (auto& package : packagesForUid) {
563 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
564 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
Sudheer Shanka03992e32018-12-12 12:43:38 -0800565 if (mountMode != VoldNativeService::REMOUNT_MODE_INSTALLER) {
566 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
567 }
568 }
569 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800570 if (BindMount(obbSourceDir, obbTargetDir) < 0) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800571 continue;
572 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700573 }
574 }
575 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700576 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700577
578 if (child == -1) {
579 PLOG(ERROR) << "Failed to fork";
580 } else {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800581 childPids.push_back(child);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700582 }
583 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800584 for (auto& child : childPids) {
585 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
586 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700587 return 0;
588}
589
Sudheer Shanka03992e32018-12-12 12:43:38 -0800590int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
Sudheer Shanka55049012019-01-09 12:15:15 -0800591 userid_t userId, struct stat& mntWriteStat,
592 struct stat& mntFullStat) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800593 struct stat storageSb;
594 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
595 PLOG(ERROR) << "Failed to stat /storage";
596 return -1;
597 }
598
599 // Some packages have access to full external storage, identify processes belonging
Sudheer Shanka55049012019-01-09 12:15:15 -0800600 // to those packages by comparing inode no.s of /mnt/runtime/full and /storage
601 if (storageSb.st_dev == mntFullStat.st_dev && storageSb.st_ino == mntFullStat.st_ino) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800602 return VoldNativeService::REMOUNT_MODE_FULL;
Sudheer Shanka55049012019-01-09 12:15:15 -0800603 } else if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
604 return VoldNativeService::REMOUNT_MODE_LEGACY;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800605 }
606
607 std::string obbMountFile =
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800608 StringPrintf("/mnt/user/%d/obb_mount/%s", userId, packagesForUid[0].c_str());
609 if (TEMP_FAILURE_RETRY(access(obbMountFile.c_str(), F_OK)) != -1) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800610 return VoldNativeService::REMOUNT_MODE_INSTALLER;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800611 } else if (errno != ENOENT) {
612 PLOG(ERROR) << "Failed to access " << obbMountFile;
613 return -1;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800614 }
615
616 // Some packages don't have access to external storage and processes belonging to
617 // those packages don't have anything mounted at /storage. So, identify those
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800618 // processes by comparing inode no.s of /mnt/user/%d/package
Sudheer Shanka03992e32018-12-12 12:43:38 -0800619 // and /storage
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800620 std::string sandbox = StringPrintf("/mnt/user/%d/package", userId);
621 struct stat sandboxStat;
622 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
623 PLOG(ERROR) << "Failed to stat " << sandbox;
624 return -1;
625 }
626 if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
627 return VoldNativeService::REMOUNT_MODE_WRITE;
628 }
629
630 return VoldNativeService::REMOUNT_MODE_NONE;
631}
632
633int VolumeManager::handleMountModeInstaller(int mountMode, int obbMountDirFd,
634 const std::string& obbMountDir,
635 const std::string& sandboxId) {
636 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
637 if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
638 return 0;
639 } else if (errno != ENOENT) {
640 PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
641 return -errno;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800642 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800643 const unique_fd fd(
644 TEMP_FAILURE_RETRY(openat(obbMountDirFd, sandboxId.c_str(), O_RDWR | O_CREAT, 0600)));
645 if (fd.get() < 0) {
646 PLOG(ERROR) << "Failed to create " << obbMountDir << "/" << sandboxId;
647 return -errno;
648 }
649 } else {
650 if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
651 if (TEMP_FAILURE_RETRY(unlinkat(obbMountDirFd, sandboxId.c_str(), 0)) == -1) {
652 PLOG(ERROR) << "Failed to unlink " << obbMountDir << "/" << sandboxId;
653 return -errno;
654 }
655 } else if (errno != ENOENT) {
656 PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
657 return -errno;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800658 }
659 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800660 return 0;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800661}
662
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700663int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
664 const std::vector<std::string>& visibleVolLabels) {
665 if (visibleVolLabels.empty()) {
666 return 0;
667 }
668 for (auto& volumeLabel : visibleVolLabels) {
669 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
670 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
671 if (isVolPrimaryEmulated) {
672 StringAppendF(&volumeRoot, "/%d", userId);
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000673 if (CreateDir(volumeRoot, 0755) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700674 return -errno;
675 }
676 }
677
678 std::string sandboxRoot =
679 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
680 if (sandboxRoot.empty()) {
681 return -errno;
682 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700683 }
Sudheer Shanka83680402019-02-24 10:16:09 -0800684
685 if (prepareSandboxTargets(userId, visibleVolLabels) < 0) {
686 return -errno;
687 }
688
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800689 if (mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1) < 0) {
690 PLOG(ERROR) << "Failed to setup sandboxes for already running processes";
691 return -errno;
692 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700693 return 0;
694}
695
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000696int VolumeManager::prepareSandboxTargets(userid_t userId,
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000697 const std::vector<std::string>& visibleVolLabels) {
698 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
699 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800700 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000701 return -errno;
702 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800703
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000704 StringAppendF(&mntTargetRoot, "/package");
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800705 if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
706 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000707 return -errno;
708 }
709
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800710 for (auto& volumeLabel : visibleVolLabels) {
711 std::string sandboxTarget =
712 StringPrintf("%s/%s", mntTargetRoot.c_str(), volumeLabel.c_str());
713 if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
714 PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
715 return -errno;
716 }
717
718 if (mPrimary && volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
719 StringAppendF(&sandboxTarget, "/%d", userId);
720 if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
721 PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
722 return -errno;
723 }
724 }
725 }
726
727 StringAppendF(&mntTargetRoot, "/self");
728 if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
729 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000730 return -errno;
731 }
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000732
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000733 if (mPrimary) {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800734 std::string pkgPrimarySource(mPrimary->getPath());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000735 if (mPrimary->isEmulated()) {
736 StringAppendF(&pkgPrimarySource, "/%d", userId);
737 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800738 StringAppendF(&mntTargetRoot, "/primary");
739 if (Symlink(pkgPrimarySource, mntTargetRoot) < 0) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000740 return -errno;
741 }
742 }
743 return 0;
744}
745
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700746std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
747 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700748 std::string path(pathPrefix);
749 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
750 for (size_t i = 0; i < subDirList.size(); ++i) {
751 std::string subDir = subDirList[i];
752 if (subDir.empty()) {
753 continue;
754 }
755 StringAppendF(&path, "/%s", subDir.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000756 if (CreateDir(path, mode) < 0) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700757 return kEmptyString;
758 }
759 }
760 return path;
761}
762
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700763bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
764 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000765 if (CreateDir(volumeAndroidRoot, 0700) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700766 return false;
767 }
768 std::array<std::string, 3> dirs = {"data", "media", "obb"};
769 for (auto& dir : dirs) {
770 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000771 if (CreateDir(path, 0700) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700772 return false;
773 }
774 }
775 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700776}
777
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700778int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
779 mAddedUsers[userId] = userSerialNumber;
780 return 0;
781}
782
783int VolumeManager::onUserRemoved(userid_t userId) {
784 mAddedUsers.erase(userId);
785 return 0;
786}
787
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700788int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
789 const std::vector<int>& appIds,
790 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700791 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700792 // Note that sometimes the system will spin up processes from Zygote
793 // before actually starting the user, so we're okay if Zygote
794 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600795 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700796 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
797
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700798 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700799 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700800 for (size_t i = 0; i < packageNames.size(); ++i) {
801 mAppIds[packageNames[i]] = appIds[i];
802 mSandboxIds[appIds[i]] = sandboxIds[i];
803 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700804 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700805 linkPrimary(userId);
806 }
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800807 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700808 std::vector<std::string> visibleVolLabels;
809 for (auto& volId : mVisibleVolumeIds) {
810 auto vol = findVolume(volId);
811 userid_t mountUserId = vol->getMountUserId();
812 if (mountUserId == userId || vol->isEmulated()) {
813 visibleVolLabels.push_back(vol->getLabel());
814 }
815 }
816 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
817 return -errno;
818 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700819 }
820 return 0;
821}
822
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700823int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700824 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700825 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700826
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800827 if (hasIsolatedStorage()) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800828 auto& userPackages = mUserPackages[userId];
829 std::string userMntTargetRoot = StringPrintf("/mnt/user/%d", userId);
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800830 std::string pkgPrimaryDir =
831 StringPrintf("%s/package/self/primary", userMntTargetRoot.c_str());
832 if (Unlink(pkgPrimaryDir) < 0) {
833 return -errno;
Sudheer Shanka023b5392019-02-06 12:39:19 -0800834 }
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700835 mUserPackages.erase(userId);
Sudheer Shanka023b5392019-02-06 12:39:19 -0800836 if (DeleteDirContentsAndDir(userMntTargetRoot) < 0) {
837 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << userMntTargetRoot;
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700838 return -errno;
839 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800840 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << userMntTargetRoot;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700841 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700842 return 0;
843}
844
Sudheer Shankad484aa92018-07-31 10:07:34 -0700845int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700846 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700847 for (size_t i = 0; i < packageNames.size(); ++i) {
848 mAppIds[packageNames[i]] = appIds[i];
849 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700850 return 0;
851}
852
853int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700854 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700855 for (size_t i = 0; i < appIds.size(); ++i) {
856 mSandboxIds[appIds[i]] = sandboxIds[i];
857 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700858 return 0;
859}
860
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700861int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
862 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800863 if (!hasIsolatedStorage()) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700864 return 0;
865 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
866 // User not started, no need to do anything now. Required bind mounts for the package will
867 // be created when the user starts.
868 return 0;
869 }
Sudheer Shanka23d725d2019-02-28 10:46:48 -0800870
871 auto& userPackages = mUserPackages[userId];
872 if (std::find(userPackages.begin(), userPackages.end(), packageName) != userPackages.end()) {
873 return 0;
874 }
875
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700876 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700877 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700878 mUserPackages[userId].push_back(packageName);
879 mAppIds[packageName] = appId;
880 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700881
882 std::vector<std::string> visibleVolLabels;
883 for (auto& volId : mVisibleVolumeIds) {
884 auto vol = findVolume(volId);
885 userid_t mountUserId = vol->getMountUserId();
886 if (mountUserId == userId || vol->isEmulated()) {
887 visibleVolLabels.push_back(vol->getLabel());
888 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700889 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700890 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700891}
892
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700893int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700894 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800895 if (!hasIsolatedStorage()) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700896 return 0;
897 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700898 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
899 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700900 auto& userPackages = mUserPackages[userId];
Sudheer Shankaba0c62f2018-12-16 18:22:34 -0800901 userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
902 userPackages.end());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700903 // If the package is not uninstalled in any other users, remove appId and sandboxId
904 // corresponding to it from the internal state.
905 bool installedInAnyUser = false;
906 for (auto& it : mUserPackages) {
907 auto& packages = it.second;
908 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
909 installedInAnyUser = true;
910 break;
911 }
912 }
913 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700914 const auto& entry = mAppIds.find(packageName);
915 if (entry != mAppIds.end()) {
916 mSandboxIds.erase(entry->second);
917 mAppIds.erase(entry);
918 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700919 }
920
921 std::vector<std::string> visibleVolLabels;
922 for (auto& volId : mVisibleVolumeIds) {
923 auto vol = findVolume(volId);
924 userid_t mountUserId = vol->getMountUserId();
925 if (mountUserId == userId || vol->isEmulated()) {
926 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
927 return -errno;
928 }
929 }
930 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800931
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700932 return 0;
933}
934
935int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
936 const std::string& sandboxId, userid_t userId,
937 const std::string& volLabel) {
938 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
939 << ", volLabel=" << volLabel;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700940
941 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
942 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
943 StringAppendF(&sandboxDir, "/%d", userId);
944 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700945 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700946
Sudheer Shanka023b5392019-02-06 12:39:19 -0800947 if (DeleteDirContentsAndDir(sandboxDir) < 0) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700948 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
949 return -errno;
950 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800951
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700952 return 0;
953}
954
Jeff Sharkey401b2602017-12-14 22:15:20 -0700955int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
956 mSecureKeyguardShowing = isShowing;
957 if (!mSecureKeyguardShowing) {
958 // Now that secure keyguard has been dismissed, process
959 // any pending disks
960 for (const auto& disk : mPendingDisks) {
961 disk->create();
962 mDisks.push_back(disk);
963 }
964 mPendingDisks.clear();
965 }
966 return 0;
967}
968
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700969int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800970 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700971 return 0;
972 }
973
974 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
975 return 0;
976 }
977
978 mVisibleVolumeIds.insert(vol->getId());
979 userid_t mountUserId = vol->getMountUserId();
980 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
981 // We don't want to create another shared_ptr here because then we will end up with
982 // two shared_ptrs owning the underlying pointer without sharing it.
983 mPrimary = findVolume(vol->getId());
984 for (userid_t userId : mStartedUsers) {
985 if (linkPrimary(userId) != 0) {
986 return -errno;
987 }
988 }
989 }
990 if (vol->isEmulated()) {
991 for (userid_t userId : mStartedUsers) {
992 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
993 return -errno;
994 }
995 }
996 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
997 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
998 return -errno;
999 }
1000 }
1001 return 0;
1002}
1003
1004int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001005 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001006 return 0;
1007 }
1008
1009 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
1010 return 0;
1011 }
1012
1013 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1014 mPrimary = nullptr;
1015 }
1016
1017 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
1018 userid_t mountUserId = vol->getMountUserId();
1019 if (vol->isEmulated()) {
1020 for (userid_t userId : mStartedUsers) {
1021 if (destroySandboxesForVol(vol, userId) != 0) {
1022 return -errno;
1023 }
1024 }
1025 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1026 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1027 return -errno;
1028 }
1029 }
1030 return 0;
1031}
1032
1033int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1034 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -08001035 std::string volSandboxRoot =
1036 StringPrintf("/mnt/user/%d/package/%s", userId, vol->getLabel().c_str());
1037 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1038 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1039 return -errno;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001040 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -08001041 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001042 return 0;
1043}
1044
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001045int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001046 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001047 return 0;
1048 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001049 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001050 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001051 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001052 }
1053 return 0;
1054}
1055
Sudheer Shanka817b9112018-12-13 17:40:28 -08001056int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001057 if (!hasIsolatedStorage()) {
Sudheer Shanka817b9112018-12-13 17:40:28 -08001058 return remountUidLegacy(uid, mountMode);
1059 }
1060
1061 appid_t appId = multiuser_get_app_id(uid);
1062 userid_t userId = multiuser_get_user_id(uid);
1063 std::vector<std::string> visibleVolLabels;
1064 for (auto& volId : mVisibleVolumeIds) {
1065 auto vol = findVolume(volId);
1066 userid_t mountUserId = vol->getMountUserId();
1067 if (mountUserId == userId || vol->isEmulated()) {
1068 visibleVolLabels.push_back(vol->getLabel());
1069 }
1070 }
1071
1072 // Finding one package with appId is enough
1073 std::vector<std::string> packageNames;
1074 for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
1075 if (it->second == appId) {
1076 packageNames.push_back(it->first);
1077 break;
1078 }
1079 }
1080 if (packageNames.empty()) {
1081 PLOG(ERROR) << "Failed to find packageName for " << uid;
Sudheer Shanka53947a32018-08-01 10:24:13 -07001082 return -1;
1083 }
Sudheer Shanka817b9112018-12-13 17:40:28 -08001084 return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
1085}
1086
1087int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
1088 std::string mode;
1089 switch (mountMode) {
1090 case VoldNativeService::REMOUNT_MODE_NONE:
1091 mode = "none";
1092 break;
1093 case VoldNativeService::REMOUNT_MODE_DEFAULT:
1094 mode = "default";
1095 break;
1096 case VoldNativeService::REMOUNT_MODE_READ:
1097 mode = "read";
1098 break;
1099 case VoldNativeService::REMOUNT_MODE_WRITE:
1100 mode = "write";
1101 break;
1102 default:
1103 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
1104 return -1;
1105 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001106 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1107
1108 DIR* dir;
1109 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001110 std::string rootName;
1111 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001112 int pidFd;
1113 int nsFd;
1114 struct stat sb;
1115 pid_t child;
1116
Jiyong Park8d21c922019-01-04 13:35:25 +09001117 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
1118
Jeff Sharkey66270a22015-06-24 11:49:24 -07001119 if (!(dir = opendir("/proc"))) {
1120 PLOG(ERROR) << "Failed to opendir";
1121 return -1;
1122 }
1123
1124 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001125 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1126 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001127 closedir(dir);
1128 return -1;
1129 }
1130
1131 // Poke through all running PIDs look for apps running as UID
1132 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001133 pid_t pid;
1134 if (de->d_type != DT_DIR) continue;
1135 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1136
Jeff Sharkey66270a22015-06-24 11:49:24 -07001137 pidFd = -1;
1138 nsFd = -1;
1139
1140 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1141 if (pidFd < 0) {
1142 goto next;
1143 }
1144 if (fstat(pidFd, &sb) != 0) {
1145 PLOG(WARNING) << "Failed to stat " << de->d_name;
1146 goto next;
1147 }
1148 if (sb.st_uid != uid) {
1149 goto next;
1150 }
1151
1152 // Matches so far, but refuse to touch if in root namespace
1153 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001154 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001155 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1156 goto next;
1157 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001158 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001159 LOG(WARNING) << "Skipping due to root namespace";
1160 goto next;
1161 }
1162
Jiyong Park8d21c922019-01-04 13:35:25 +09001163 if (apexUpdatable) {
1164 std::string exeName;
1165 // When ro.apex.bionic_updatable is set to true,
1166 // some early native processes have mount namespaces that are different
1167 // from that of the init. Therefore, above check can't filter them out.
1168 // Since the propagation type of / is 'shared', unmounting /storage
1169 // for the early native processes affects other processes including
1170 // init. Filter out such processes by skipping if a process is a
1171 // non-Java process whose UID is < AID_APP_START. (The UID condition
1172 // is required to not filter out child processes spawned by apps.)
1173 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
1174 PLOG(WARNING) << "Failed to read exe name for " << de->d_name;
1175 goto next;
1176 }
1177 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
1178 LOG(WARNING) << "Skipping due to native system process";
1179 goto next;
1180 }
1181 }
1182
Jeff Sharkey66270a22015-06-24 11:49:24 -07001183 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -07001184 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
1185 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001186 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001187 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001188 goto next;
1189 }
1190
1191 if (!(child = fork())) {
1192 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001193 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001194 _exit(1);
1195 }
1196
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001197 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001198
1199 std::string storageSource;
1200 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001201 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001202 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001203 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001204 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001205 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001206 } else {
1207 // Sane default of no storage visible
1208 _exit(0);
1209 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001210 if (TEMP_FAILURE_RETRY(
1211 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1212 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001213 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001214 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001215 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1216 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001217 _exit(1);
1218 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001219
1220 // Mount user-specific symlink helper into place
1221 userid_t user_id = multiuser_get_user_id(uid);
1222 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001223 if (TEMP_FAILURE_RETRY(
1224 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1225 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001226 _exit(1);
1227 }
1228
Jeff Sharkey66270a22015-06-24 11:49:24 -07001229 _exit(0);
1230 }
1231
1232 if (child == -1) {
1233 PLOG(ERROR) << "Failed to fork";
1234 goto next;
1235 } else {
1236 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1237 }
1238
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001239 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001240 close(nsFd);
1241 close(pidFd);
1242 }
1243 closedir(dir);
1244 return 0;
1245}
1246
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001247int VolumeManager::reset() {
1248 // Tear down all existing disks/volumes and start from a blank slate so
1249 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001250 if (mInternalEmulated != nullptr) {
1251 mInternalEmulated->destroy();
1252 mInternalEmulated->create();
1253 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001254 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001255 disk->destroy();
1256 disk->create();
1257 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001258 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001259 mAddedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001260
1261 mUserPackages.clear();
1262 mAppIds.clear();
1263 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001264 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001265
Sudheer Shanka023b5392019-02-06 12:39:19 -08001266 for (userid_t userId : mStartedUsers) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001267 DeleteDirContents(StringPrintf("/mnt/user/%d/package", userId));
Sudheer Shanka023b5392019-02-06 12:39:19 -08001268 }
1269 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001270 return 0;
1271}
1272
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001273// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001274int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001275 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001276 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001277 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001278 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001279 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001280 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001281 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001282 disk->destroy();
1283 }
Risan8c9f3322018-10-29 08:52:56 +09001284 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001285 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001286 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001287 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001288 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001289}
1290
Jeff Sharkey9c484982015-03-31 10:35:33 -07001291int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001292 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001293 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001294
Jeff Sharkey9c484982015-03-31 10:35:33 -07001295 // First, try gracefully unmounting all known devices
1296 if (mInternalEmulated != nullptr) {
1297 mInternalEmulated->unmount();
1298 }
Risan8c9f3322018-10-29 08:52:56 +09001299 for (const auto& stub : mStubVolumes) {
1300 stub->unmount();
1301 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001302 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001303 disk->unmountAll();
1304 }
1305
1306 // Worst case we might have some stale mounts lurking around, so
1307 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001308 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001309 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001310 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001311 return -errno;
1312 }
1313
1314 // Some volumes can be stacked on each other, so force unmount in
1315 // reverse order to give us the best chance of success.
1316 std::list<std::string> toUnmount;
1317 mntent* mentry;
1318 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001319 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001320 if ((StartsWith(test, "/mnt/") &&
1321#ifdef __ANDROID_DEBUGGABLE__
1322 !StartsWith(test, "/mnt/scratch") &&
1323#endif
1324 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1325 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001326 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001327 }
1328 }
1329 endmntent(fp);
1330
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001331 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001332 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001333 android::vold::ForceUnmount(path);
1334 }
1335
1336 return 0;
1337}
1338
Jeff Sharkey3472e522017-10-06 18:02:53 -06001339int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001340 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001341 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001342 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001343 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001344 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001345 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001346 return -EINVAL;
1347 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001348}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001349
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001350int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001351 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001352 int id = mNextObbId++;
1353
1354 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001355 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001356 vol->create();
1357
1358 mObbVolumes.push_back(vol);
1359 *outVolId = vol->getId();
1360 return android::OK;
1361}
1362
1363int VolumeManager::destroyObb(const std::string& volId) {
1364 auto i = mObbVolumes.begin();
1365 while (i != mObbVolumes.end()) {
1366 if ((*i)->getId() == volId) {
1367 (*i)->destroy();
1368 i = mObbVolumes.erase(i);
1369 } else {
1370 ++i;
1371 }
1372 }
1373 return android::OK;
1374}
1375
Risan8c9f3322018-10-29 08:52:56 +09001376int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1377 const std::string& fsType, const std::string& fsUuid,
1378 const std::string& fsLabel, std::string* outVolId) {
1379 int id = mNextStubVolumeId++;
1380 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1381 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1382 vol->create();
1383
1384 mStubVolumes.push_back(vol);
1385 *outVolId = vol->getId();
1386 return android::OK;
1387}
1388
1389int VolumeManager::destroyStubVolume(const std::string& volId) {
1390 auto i = mStubVolumes.begin();
1391 while (i != mStubVolumes.end()) {
1392 if ((*i)->getId() == volId) {
1393 (*i)->destroy();
1394 i = mStubVolumes.erase(i);
1395 } else {
1396 ++i;
1397 }
1398 }
1399 return android::OK;
1400}
1401
Risan8f6198d2018-10-26 20:56:45 -06001402int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001403 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001404}
1405
Risan8f6198d2018-10-26 20:56:45 -06001406int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001407 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001408}
1409
1410int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001411 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001412}