blob: f600f646f87d9d36a801203e926f4ceab7de73ac [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080022#include <mntent.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080028#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070029#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070030#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070033#include <array>
San Mehata19b2502010-01-06 10:33:53 -080034
San Mehata2677e42009-12-13 10:40:18 -080035#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070036
Elliott Hughes7e128fb2015-12-04 15:50:53 -080037#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070038#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060039#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080040#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070041#include <android-base/strings.h>
42
Jeff Sharkey71ebe152013-09-17 17:24:38 -070043#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060044#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070045
Robert Craigb9e3ba52014-02-04 10:53:00 -050046#include <selinux/android.h>
47
San Mehatfd7f5872009-10-12 11:32:47 -070048#include <sysutils/NetlinkEvent.h>
49
Kenny Root344ca102012-04-03 17:23:01 -070050#include <private/android_filesystem_config.h>
51
Eric Biggersa701c452018-10-23 13:06:55 -070052#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070053
Risanac02a482018-10-31 21:59:47 -060054#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070055#include "Devmapper.h"
Eric Biggersa701c452018-10-23 13:06:55 -070056#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080057#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070058#include "NetlinkManager.h"
59#include "Process.h"
60#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070061#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070062#include "VoldUtil.h"
63#include "VolumeManager.h"
64#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070065#include "fs/Ext4.h"
66#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070067#include "model/EmulatedVolume.h"
68#include "model/ObbVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090069#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080070
Sudheer Shanka53947a32018-08-01 10:24:13 -070071using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070072using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070073using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070074using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060075using android::base::unique_fd;
Sudheer Shanka03992e32018-12-12 12:43:38 -080076using android::vold::VoldNativeService;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070077
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060078static const char* kPathUserMount = "/mnt/user";
79static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
80
Sudheer Shanka53947a32018-08-01 10:24:13 -070081static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Sudheer Shanka34b437b2019-01-17 17:20:47 -080082static const char* kIsolatedStorageSnapshot = "sys.isolated_storage_snapshot";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060083static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
84
Sudheer Shanka53947a32018-08-01 10:24:13 -070085static const std::string kEmptyString("");
86
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060087/* 512MiB is large enough for testing purposes */
88static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070089
Jeff Sharkey36801cc2015-03-13 16:09:20 -070090static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080091static const unsigned int kMajorBlockExperimentalMin = 240;
92static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070093
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070094VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070095
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070096VolumeManager* VolumeManager::Instance() {
97 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070098 return sInstance;
99}
100
101VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800102 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600103 mNextObbId = 0;
Risan8c9f3322018-10-29 08:52:56 +0900104 mNextStubVolumeId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700105 // For security reasons, assume that a secure keyguard is
106 // showing until we hear otherwise
107 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700108}
109
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700110VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800111
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800112static bool hasIsolatedStorage() {
113 return GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, false));
114}
115
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600116int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600117 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700118 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600119 if (access(kPathVirtualDisk, F_OK) != 0) {
120 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
121 }
122
123 if (mVirtualDisk == nullptr) {
124 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
125 LOG(ERROR) << "Failed to create virtual disk";
126 return -1;
127 }
128
129 struct stat buf;
130 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
131 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
132 return -1;
133 }
134
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700135 auto disk = new android::vold::Disk(
136 "virtual", buf.st_rdev, "virtual",
137 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600138 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700139 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600140 }
141 } else {
142 if (mVirtualDisk != nullptr) {
143 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700144 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600145
146 Loop::destroyByDevice(mVirtualDiskPath.c_str());
147 mVirtualDisk = nullptr;
148 }
149
150 if (access(kPathVirtualDisk, F_OK) == 0) {
151 unlink(kPathVirtualDisk);
152 }
153 }
154 return 0;
155}
156
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700157int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800158 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700159 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800160}
161
San Mehatf1b736b2009-10-10 17:22:08 -0700162int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600163 ATRACE_NAME("VolumeManager::start");
164
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700165 // Always start from a clean slate by unmounting everything in
166 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700167 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700168
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600169 Devmapper::destroyAll();
170 Loop::destroyAll();
171
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700172 // Assume that we always have an emulated volume on internal
173 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700174 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700175 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700176 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 mInternalEmulated->create();
178
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600179 // Consider creating a virtual disk
180 updateVirtualDisk();
181
San Mehatf1b736b2009-10-10 17:22:08 -0700182 return 0;
183}
184
185int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700186 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700187 mInternalEmulated->destroy();
188 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700189 return 0;
190}
191
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700192void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700193 std::lock_guard<std::mutex> lock(mLock);
194
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700195 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700196 LOG(DEBUG) << "----------------";
197 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700198 evt->dump();
199 }
San Mehatf1b736b2009-10-10 17:22:08 -0700200
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700201 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
202 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700203
204 if (devType != "disk") return;
205
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600206 int major = std::stoi(evt->findParam("MAJOR"));
207 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700208 dev_t device = makedev(major, minor);
209
210 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700211 case NetlinkEvent::Action::kAdd: {
212 for (const auto& source : mDiskSources) {
213 if (source->matches(eventPath)) {
214 // For now, assume that MMC and virtio-blk (the latter is
215 // emulator-specific; see Disk.cpp for details) devices are SD,
216 // and that everything else is USB
217 int flags = source->getFlags();
218 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
219 major >= (int)kMajorBlockExperimentalMin &&
220 major <= (int)kMajorBlockExperimentalMax)) {
221 flags |= android::vold::Disk::Flags::kSd;
222 } else {
223 flags |= android::vold::Disk::Flags::kUsb;
224 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700225
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700226 auto disk =
227 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
228 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
229 break;
230 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700231 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700232 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700233 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700234 case NetlinkEvent::Action::kChange: {
235 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
236 handleDiskChanged(device);
237 break;
238 }
239 case NetlinkEvent::Action::kRemove: {
240 handleDiskRemoved(device);
241 break;
242 }
243 default: {
244 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
245 break;
246 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700247 }
248}
249
Jeff Sharkey401b2602017-12-14 22:15:20 -0700250void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
251 // For security reasons, if secure keyguard is showing, wait
252 // until the user unlocks the device to actually touch it
253 if (mSecureKeyguardShowing) {
254 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700255 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700256 mPendingDisks.push_back(disk);
257 } else {
258 disk->create();
259 mDisks.push_back(disk);
260 }
261}
262
263void VolumeManager::handleDiskChanged(dev_t device) {
264 for (const auto& disk : mDisks) {
265 if (disk->getDevice() == device) {
266 disk->readMetadata();
267 disk->readPartitions();
268 }
269 }
270
271 // For security reasons, we ignore all pending disks, since
272 // we'll scan them once the device is unlocked
273}
274
275void VolumeManager::handleDiskRemoved(dev_t device) {
276 auto i = mDisks.begin();
277 while (i != mDisks.end()) {
278 if ((*i)->getDevice() == device) {
279 (*i)->destroy();
280 i = mDisks.erase(i);
281 } else {
282 ++i;
283 }
284 }
285 auto j = mPendingDisks.begin();
286 while (j != mPendingDisks.end()) {
287 if ((*j)->getDevice() == device) {
288 j = mPendingDisks.erase(j);
289 } else {
290 ++j;
291 }
292 }
293}
294
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700295void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800296 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700297 mDiskSources.push_back(diskSource);
298}
299
300std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
301 for (auto disk : mDisks) {
302 if (disk->getId() == id) {
303 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700304 }
305 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700306 return nullptr;
307}
San Mehatf1b736b2009-10-10 17:22:08 -0700308
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700309std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800310 // Vold could receive "mount" after "shutdown" command in the extreme case.
311 // If this happens, mInternalEmulated will equal nullptr and
312 // we need to deal with it in order to avoid null pointer crash.
313 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700314 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700315 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700316 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700317 auto vol = disk->findVolume(id);
318 if (vol != nullptr) {
319 return vol;
320 }
321 }
Risan8c9f3322018-10-29 08:52:56 +0900322 for (const auto& vol : mStubVolumes) {
323 if (vol->getId() == id) {
324 return vol;
325 }
326 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600327 for (const auto& vol : mObbVolumes) {
328 if (vol->getId() == id) {
329 return vol;
330 }
331 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700332 return nullptr;
333}
334
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800335void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
336 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700337 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700338 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700339 disk->listVolumes(type, list);
340 }
341}
342
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600343int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700344 std::string normalizedGuid;
345 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
346 LOG(WARNING) << "Invalid GUID " << partGuid;
347 return -1;
348 }
349
Paul Crowleyc6433a22017-10-24 14:54:43 -0700350 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700351 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
352 if (unlink(keyPath.c_str()) != 0) {
353 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700354 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700355 }
Eric Biggersa701c452018-10-23 13:06:55 -0700356 if (fscrypt_is_native()) {
357 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700358 success = false;
359 }
360 }
361 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700362}
363
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700364int VolumeManager::linkPrimary(userid_t userId) {
365 std::string source(mPrimary->getPath());
366 if (mPrimary->isEmulated()) {
367 source = StringPrintf("%s/%d", source.c_str(), userId);
368 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
369 }
370
371 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
372 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
373 if (errno != ENOENT) {
374 PLOG(WARNING) << "Failed to unlink " << target;
375 }
376 }
377 LOG(DEBUG) << "Linking " << source << " to " << target;
378 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
379 PLOG(WARNING) << "Failed to link";
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700380 return -errno;
381 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700382 return 0;
383}
384
385int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
386 const std::string& mntTargetRoot,
387 const std::string& packageName, const char* dirName) {
388 std::string mntSourceDir =
389 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
390 std::string mntTargetDir =
391 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
392 if (umount2(mntTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL && errno != ENOENT) {
393 PLOG(ERROR) << "Failed to unmount " << mntTargetDir;
394 return -1;
395 }
396 if (TEMP_FAILURE_RETRY(mount(mntSourceDir.c_str(), mntTargetDir.c_str(), nullptr,
397 MS_BIND | MS_REC, nullptr)) == -1) {
398 PLOG(ERROR) << "Failed to mount " << mntSourceDir << " to " << mntTargetDir;
399 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700400 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700401 if (TEMP_FAILURE_RETRY(
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700402 mount(nullptr, mntTargetDir.c_str(), nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
403 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTargetDir;
404 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700405 }
406 return 0;
407}
408
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700409int VolumeManager::mountPkgSpecificDirsForRunningProcs(
410 userid_t userId, const std::vector<std::string>& packageNames,
Sudheer Shanka817b9112018-12-13 17:40:28 -0800411 const std::vector<std::string>& visibleVolLabels, int remountMode) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700412 // TODO: New processes could be started while traversing over the existing
413 // processes which would end up not having the necessary bind mounts. This
414 // issue needs to be fixed, may be by doing multiple passes here?
415 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
416 if (!dirp) {
417 PLOG(ERROR) << "Failed to opendir /proc";
418 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700419 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700420
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700421 std::string rootName;
422 // Figure out root namespace to compare against below
423 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
424 PLOG(ERROR) << "Failed to read root namespace";
425 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700426 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700427
Sudheer Shanka55049012019-01-09 12:15:15 -0800428 struct stat mntFullSb;
429 struct stat mntWriteSb;
430 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/full", &mntFullSb)) == -1) {
431 PLOG(ERROR) << "Failed to stat /mnt/runtime/full";
432 return -1;
433 }
434 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &mntWriteSb)) == -1) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700435 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
436 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700437 }
438
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700439 std::unordered_set<appid_t> validAppIds;
440 for (auto& package : packageNames) {
441 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700442 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700443 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700444
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700445 struct dirent* de;
446 // Poke through all running PIDs look for apps running in userId
447 while ((de = readdir(dirp.get()))) {
448 pid_t pid;
449 if (de->d_type != DT_DIR) continue;
450 if (!android::base::ParseInt(de->d_name, &pid)) continue;
451
452 const unique_fd pidFd(
453 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
454 if (pidFd.get() < 0) {
455 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700456 continue;
457 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700458 struct stat sb;
459 if (fstat(pidFd.get(), &sb) != 0) {
460 PLOG(WARNING) << "Failed to stat " << de->d_name;
461 continue;
462 }
463 if (multiuser_get_user_id(sb.st_uid) != userId) {
464 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700465 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700466
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700467 // Matches so far, but refuse to touch if in root namespace
468 LOG(VERBOSE) << "Found matching PID " << de->d_name;
469 std::string pidName;
470 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
471 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
472 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700473 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700474 if (rootName == pidName) {
475 LOG(WARNING) << "Skipping due to root namespace";
476 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700477 }
478
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700479 // Only update the mount points of processes running with one of validAppIds.
480 // This should skip any isolated uids.
481 appid_t appId = multiuser_get_app_id(sb.st_uid);
482 if (validAppIds.find(appId) == validAppIds.end()) {
483 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700484 }
485
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700486 std::vector<std::string> packagesForUid;
487 for (auto& package : userPackages) {
488 if (mAppIds[package] == appId) {
489 packagesForUid.push_back(package);
490 }
491 }
492 if (packagesForUid.empty()) {
493 continue;
494 }
495 const std::string& sandboxId = mSandboxIds[appId];
496
497 // We purposefully leave the namespace open across the fork
498 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
499 if (nsFd.get() < 0) {
500 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
501 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700502 }
503
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700504 pid_t child;
505 if (!(child = fork())) {
506 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
507 PLOG(ERROR) << "Failed to setns for " << de->d_name;
508 _exit(1);
509 }
510
Sudheer Shanka817b9112018-12-13 17:40:28 -0800511 int mountMode;
512 if (remountMode == -1) {
Sudheer Shanka55049012019-01-09 12:15:15 -0800513 mountMode =
514 getMountModeForRunningProc(packagesForUid, userId, mntWriteSb, mntFullSb);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800515 if (mountMode == -1) {
516 _exit(1);
517 }
518 } else {
519 mountMode = remountMode;
520 std::string obbMountFile = StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId,
521 packagesForUid[0].c_str());
522 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
523 if (access(obbMountFile.c_str(), F_OK) != 0) {
524 const unique_fd fd(
525 TEMP_FAILURE_RETRY(open(obbMountFile.c_str(), O_RDWR | O_CREAT, 0660)));
526 }
527 } else {
528 if (access(obbMountFile.c_str(), F_OK) == 0) {
529 remove(obbMountFile.c_str());
530 }
531 }
532 }
533 if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
Sudheer Shanka55049012019-01-09 12:15:15 -0800534 mountMode == VoldNativeService::REMOUNT_MODE_LEGACY ||
Sudheer Shanka817b9112018-12-13 17:40:28 -0800535 mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
536 // These mount modes are not going to change dynamically, so don't bother
537 // unmounting/remounting dirs.
538 _exit(0);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700539 }
540
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700541 for (auto& volumeLabel : visibleVolLabels) {
542 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
543 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
544 if (volumeLabel == "emulated") {
545 StringAppendF(&mntSource, "/%d", userId);
546 StringAppendF(&mntTarget, "/%d", userId);
547 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800548 std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
549 std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
550 if (umount2(obbTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
551 errno != ENOENT) {
552 PLOG(ERROR) << "Failed to unmount " << obbTargetDir;
553 continue;
554 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700555 for (auto& package : packagesForUid) {
556 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
557 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
Sudheer Shanka03992e32018-12-12 12:43:38 -0800558 if (mountMode != VoldNativeService::REMOUNT_MODE_INSTALLER) {
559 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
560 }
561 }
562 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800563 if (TEMP_FAILURE_RETRY(mount(obbSourceDir.c_str(), obbTargetDir.c_str(),
564 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
565 PLOG(ERROR) << "Failed to mount " << obbSourceDir << " to " << obbTargetDir;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800566 continue;
567 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800568 if (TEMP_FAILURE_RETRY(mount(nullptr, obbTargetDir.c_str(), nullptr,
Sudheer Shanka03992e32018-12-12 12:43:38 -0800569 MS_REC | MS_SLAVE, nullptr)) == -1) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800570 PLOG(ERROR) << "Failed to set MS_SLAVE at " << obbTargetDir.c_str();
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 {
581 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700582 }
583 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700584 return 0;
585}
586
Sudheer Shanka03992e32018-12-12 12:43:38 -0800587int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
Sudheer Shanka55049012019-01-09 12:15:15 -0800588 userid_t userId, struct stat& mntWriteStat,
589 struct stat& mntFullStat) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800590 struct stat storageSb;
591 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
592 PLOG(ERROR) << "Failed to stat /storage";
593 return -1;
594 }
595
596 // Some packages have access to full external storage, identify processes belonging
Sudheer Shanka55049012019-01-09 12:15:15 -0800597 // to those packages by comparing inode no.s of /mnt/runtime/full and /storage
598 if (storageSb.st_dev == mntFullStat.st_dev && storageSb.st_ino == mntFullStat.st_ino) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800599 return VoldNativeService::REMOUNT_MODE_FULL;
Sudheer Shanka55049012019-01-09 12:15:15 -0800600 } else if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
601 return VoldNativeService::REMOUNT_MODE_LEGACY;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800602 }
603
604 std::string obbMountFile =
605 StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId, packagesForUid[0].c_str());
606 if (access(obbMountFile.c_str(), F_OK) == 0) {
607 return VoldNativeService::REMOUNT_MODE_INSTALLER;
608 }
609
610 // Some packages don't have access to external storage and processes belonging to
611 // those packages don't have anything mounted at /storage. So, identify those
612 // processes by comparing inode no.s of /mnt/user/%d/package/%s
613 // and /storage
614 for (auto& package : packagesForUid) {
615 std::string sandbox = StringPrintf("/mnt/user/%d/package/%s", userId, package.c_str());
616 struct stat sandboxStat;
617 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
618 PLOG(ERROR) << "Failed to stat " << sandbox;
619 return -1;
620 }
621 if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
622 return VoldNativeService::REMOUNT_MODE_WRITE;
623 }
624 }
625 return VoldNativeService::REMOUNT_MODE_NONE;
626}
627
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700628int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
629 const std::vector<std::string>& visibleVolLabels) {
630 if (visibleVolLabels.empty()) {
631 return 0;
632 }
633 for (auto& volumeLabel : visibleVolLabels) {
634 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
635 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
636 if (isVolPrimaryEmulated) {
637 StringAppendF(&volumeRoot, "/%d", userId);
638 if (fs_prepare_dir(volumeRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
639 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeRoot;
640 return -errno;
641 }
642 }
643
644 std::string sandboxRoot =
645 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
646 if (sandboxRoot.empty()) {
647 return -errno;
648 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700649
650 if (!createPkgSpecificDirRoots(volumeRoot)) {
651 return -errno;
652 }
653
654 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
655 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
656 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
657 return -errno;
658 }
659 mntTargetRoot.append("/package");
660 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
661 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
662 return -errno;
663 }
664
665 for (auto& packageName : packageNames) {
666 const auto& it = mAppIds.find(packageName);
667 if (it == mAppIds.end()) {
668 PLOG(ERROR) << "appId is not available for " << packageName;
669 continue;
670 }
671 appid_t appId = it->second;
672 std::string sandboxId = mSandboxIds[appId];
673 uid_t uid = multiuser_get_uid(userId, appId);
674
675 // [1] Create /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
676 // [2] Create /mnt/user/0/package/<packageName>/emulated/0
677 // Mount [1] at [2]
678 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
679 if (pkgSandboxSourceDir.empty()) {
680 return -errno;
681 }
682 std::string pkgSandboxTargetDir = prepareSandboxTarget(
683 packageName, uid, volumeLabel, mntTargetRoot, isVolPrimaryEmulated);
684 if (pkgSandboxTargetDir.empty()) {
685 return -errno;
686 }
687 if (umount2(pkgSandboxTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
688 errno != ENOENT) {
689 PLOG(ERROR) << "Failed to unmount " << pkgSandboxTargetDir;
690 return -errno;
691 }
692 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
693 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
694 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
695 << pkgSandboxTargetDir;
696 return -errno;
697 }
698 if (TEMP_FAILURE_RETRY(mount(nullptr, pkgSandboxTargetDir.c_str(), nullptr,
699 MS_SLAVE | MS_REC, nullptr)) == -1) {
700 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
701 << pkgSandboxTargetDir;
702 return -errno;
703 }
704
705 // Create Android/{data,media,obb}/<packageName> segments at
706 // [1] /mnt/runtime/write/emulated/0/ and
707 // [2] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>/emulated/0/
708 if (!createPkgSpecificDirs(packageName, uid, volumeRoot, pkgSandboxSourceDir)) {
709 return -errno;
710 }
711
712 if (volumeLabel == mPrimary->getLabel()) {
713 // Create [1] /mnt/user/0/package/<packageName>/self/
714 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
715 // Mount [2] at [1]
716 std::string pkgPrimaryTargetDir =
717 StringPrintf("%s/%s/self", mntTargetRoot.c_str(), packageName.c_str());
718 if (fs_prepare_dir(pkgPrimaryTargetDir.c_str(), 0755, uid, uid) != 0) {
719 PLOG(ERROR) << "Failed to fs_prepare_dir on " << pkgPrimaryTargetDir;
720 return -errno;
721 }
722 StringAppendF(&pkgPrimaryTargetDir, "/primary");
723 std::string primarySource(mPrimary->getPath());
724 if (isVolPrimaryEmulated) {
725 StringAppendF(&primarySource, "/%d", userId);
726 }
727 if (TEMP_FAILURE_RETRY(unlink(pkgPrimaryTargetDir.c_str()))) {
728 if (errno != ENOENT) {
729 PLOG(ERROR) << "Failed to unlink " << pkgPrimaryTargetDir;
730 }
731 }
732 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), pkgPrimaryTargetDir.c_str()))) {
733 PLOG(ERROR) << "Failed to link " << primarySource << " at "
734 << pkgPrimaryTargetDir;
735 return -errno;
736 }
737 }
738 }
739 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800740 mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700741 return 0;
742}
743
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700744std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
745 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700746 std::string path(pathPrefix);
747 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
748 for (size_t i = 0; i < subDirList.size(); ++i) {
749 std::string subDir = subDirList[i];
750 if (subDir.empty()) {
751 continue;
752 }
753 StringAppendF(&path, "/%s", subDir.c_str());
754 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
755 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
756 return kEmptyString;
757 }
758 }
759 return path;
760}
761
762std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700763 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700764 std::string sandboxSourceDir(sandboxRootDir);
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700765 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700766 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
767 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
768 return kEmptyString;
769 }
770 return sandboxSourceDir;
771}
772
773std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700774 const std::string& volumeLabel,
775 const std::string& mntTargetRootDir,
776 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700777 std::string segment;
778 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700779 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
780 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700781 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700782 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700783 }
784 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
785}
786
787std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700788 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700789 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
790 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
791 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
792 return kEmptyString;
793 }
794 return dataSourceDir;
795}
796
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700797bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
798 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
799 if (fs_prepare_dir(volumeAndroidRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
800 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeAndroidRoot;
801 return false;
802 }
803 std::array<std::string, 3> dirs = {"data", "media", "obb"};
804 for (auto& dir : dirs) {
805 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
806 if (fs_prepare_dir(path.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
807 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
808 return false;
809 }
810 }
811 return true;
812}
813
814bool VolumeManager::createPkgSpecificDirs(const std::string& packageName, uid_t uid,
815 const std::string& volumeRoot,
816 const std::string& sandboxDirRoot) {
817 std::array<std::string, 3> dirs = {"data", "media", "obb"};
818 for (auto& dir : dirs) {
819 std::string sourceDir = StringPrintf("%s/Android/%s", volumeRoot.c_str(), dir.c_str());
820 if (prepareSubDirs(sourceDir, packageName, 0755, uid, uid).empty()) {
821 return false;
822 }
823 std::string sandboxSegment =
824 StringPrintf("Android/%s/%s/", dir.c_str(), packageName.c_str());
825 if (prepareSubDirs(sandboxDirRoot, sandboxSegment, 0755, uid, uid).empty()) {
826 return false;
827 }
828 }
829 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700830}
831
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700832int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
833 mAddedUsers[userId] = userSerialNumber;
834 return 0;
835}
836
837int VolumeManager::onUserRemoved(userid_t userId) {
838 mAddedUsers.erase(userId);
839 return 0;
840}
841
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700842int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
843 const std::vector<int>& appIds,
844 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700845 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700846 // Note that sometimes the system will spin up processes from Zygote
847 // before actually starting the user, so we're okay if Zygote
848 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600849 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700850 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
851
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700852 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700853 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700854 for (size_t i = 0; i < packageNames.size(); ++i) {
855 mAppIds[packageNames[i]] = appIds[i];
856 mSandboxIds[appIds[i]] = sandboxIds[i];
857 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700858 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700859 linkPrimary(userId);
860 }
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800861 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700862 std::vector<std::string> visibleVolLabels;
863 for (auto& volId : mVisibleVolumeIds) {
864 auto vol = findVolume(volId);
865 userid_t mountUserId = vol->getMountUserId();
866 if (mountUserId == userId || vol->isEmulated()) {
867 visibleVolLabels.push_back(vol->getLabel());
868 }
869 }
870 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
871 return -errno;
872 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700873 }
874 return 0;
875}
876
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700877int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700878 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700879 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700880
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800881 if (hasIsolatedStorage()) {
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700882 mUserPackages.erase(userId);
883 std::string mntTargetDir = StringPrintf("/mnt/user/%d", userId);
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800884 if (android::vold::UnmountTreeWithPrefix(mntTargetDir) < 0) {
885 PLOG(ERROR) << "UnmountTreeWithPrefix on " << mntTargetDir << " failed";
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700886 return -errno;
887 }
888 if (android::vold::DeleteDirContentsAndDir(mntTargetDir) < 0) {
889 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << mntTargetDir;
890 return -errno;
891 }
892 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << mntTargetDir;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700893 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700894 return 0;
895}
896
Sudheer Shankad484aa92018-07-31 10:07:34 -0700897int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700898 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700899 for (size_t i = 0; i < packageNames.size(); ++i) {
900 mAppIds[packageNames[i]] = appIds[i];
901 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700902 return 0;
903}
904
905int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700906 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700907 for (size_t i = 0; i < appIds.size(); ++i) {
908 mSandboxIds[appIds[i]] = sandboxIds[i];
909 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700910 return 0;
911}
912
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700913int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
914 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800915 if (!hasIsolatedStorage()) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700916 return 0;
917 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
918 // User not started, no need to do anything now. Required bind mounts for the package will
919 // be created when the user starts.
920 return 0;
921 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700922 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700923 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700924 mUserPackages[userId].push_back(packageName);
925 mAppIds[packageName] = appId;
926 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700927
928 std::vector<std::string> visibleVolLabels;
929 for (auto& volId : mVisibleVolumeIds) {
930 auto vol = findVolume(volId);
931 userid_t mountUserId = vol->getMountUserId();
932 if (mountUserId == userId || vol->isEmulated()) {
933 visibleVolLabels.push_back(vol->getLabel());
934 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700935 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700936 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700937}
938
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700939int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700940 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800941 if (!hasIsolatedStorage()) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700942 return 0;
943 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700944 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
945 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700946 auto& userPackages = mUserPackages[userId];
Sudheer Shankaba0c62f2018-12-16 18:22:34 -0800947 userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
948 userPackages.end());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700949 // If the package is not uninstalled in any other users, remove appId and sandboxId
950 // corresponding to it from the internal state.
951 bool installedInAnyUser = false;
952 for (auto& it : mUserPackages) {
953 auto& packages = it.second;
954 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
955 installedInAnyUser = true;
956 break;
957 }
958 }
959 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700960 const auto& entry = mAppIds.find(packageName);
961 if (entry != mAppIds.end()) {
962 mSandboxIds.erase(entry->second);
963 mAppIds.erase(entry);
964 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700965 }
966
967 std::vector<std::string> visibleVolLabels;
968 for (auto& volId : mVisibleVolumeIds) {
969 auto vol = findVolume(volId);
970 userid_t mountUserId = vol->getMountUserId();
971 if (mountUserId == userId || vol->isEmulated()) {
972 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
973 return -errno;
974 }
975 }
976 }
977 return 0;
978}
979
980int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
981 const std::string& sandboxId, userid_t userId,
982 const std::string& volLabel) {
983 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
984 << ", volLabel=" << volLabel;
985 std::string pkgSandboxTarget =
986 StringPrintf("/mnt/user/%d/package/%s", userId, packageName.c_str());
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800987 if (android::vold::UnmountTreeWithPrefix(pkgSandboxTarget) < 0) {
988 PLOG(ERROR) << "UnmountTreeWithPrefix failed on " << pkgSandboxTarget;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700989 }
990
991 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
992 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
993 StringAppendF(&sandboxDir, "/%d", userId);
994 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700995 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700996
997 if (android::vold::DeleteDirContentsAndDir(sandboxDir) < 0) {
998 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
999 return -errno;
1000 }
1001 return 0;
1002}
1003
Jeff Sharkey401b2602017-12-14 22:15:20 -07001004int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
1005 mSecureKeyguardShowing = isShowing;
1006 if (!mSecureKeyguardShowing) {
1007 // Now that secure keyguard has been dismissed, process
1008 // any pending disks
1009 for (const auto& disk : mPendingDisks) {
1010 disk->create();
1011 mDisks.push_back(disk);
1012 }
1013 mPendingDisks.clear();
1014 }
1015 return 0;
1016}
1017
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001018int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001019 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001020 return 0;
1021 }
1022
1023 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
1024 return 0;
1025 }
1026
1027 mVisibleVolumeIds.insert(vol->getId());
1028 userid_t mountUserId = vol->getMountUserId();
1029 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1030 // We don't want to create another shared_ptr here because then we will end up with
1031 // two shared_ptrs owning the underlying pointer without sharing it.
1032 mPrimary = findVolume(vol->getId());
1033 for (userid_t userId : mStartedUsers) {
1034 if (linkPrimary(userId) != 0) {
1035 return -errno;
1036 }
1037 }
1038 }
1039 if (vol->isEmulated()) {
1040 for (userid_t userId : mStartedUsers) {
1041 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
1042 return -errno;
1043 }
1044 }
1045 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1046 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
1047 return -errno;
1048 }
1049 }
1050 return 0;
1051}
1052
1053int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001054 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001055 return 0;
1056 }
1057
1058 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
1059 return 0;
1060 }
1061
1062 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1063 mPrimary = nullptr;
1064 }
1065
1066 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
1067 userid_t mountUserId = vol->getMountUserId();
1068 if (vol->isEmulated()) {
1069 for (userid_t userId : mStartedUsers) {
1070 if (destroySandboxesForVol(vol, userId) != 0) {
1071 return -errno;
1072 }
1073 }
1074 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1075 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1076 return -errno;
1077 }
1078 }
1079 return 0;
1080}
1081
1082int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1083 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
1084 const std::vector<std::string>& packageNames = mUserPackages[userId];
1085 for (auto& packageName : packageNames) {
1086 std::string volSandboxRoot = StringPrintf("/mnt/user/%d/package/%s/%s", userId,
1087 packageName.c_str(), vol->getLabel().c_str());
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001088 if (android::vold::UnmountTreeWithPrefix(volSandboxRoot) < 0) {
1089 PLOG(ERROR) << "UnmountTreeWithPrefix on " << volSandboxRoot << " failed";
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001090 continue;
1091 }
1092 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1093 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1094 continue;
1095 }
1096 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
1097 }
1098 return 0;
1099}
1100
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001101int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001102 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001103 return 0;
1104 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001105 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001106 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001107 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001108 }
1109 return 0;
1110}
1111
Sudheer Shanka817b9112018-12-13 17:40:28 -08001112int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001113 if (!hasIsolatedStorage()) {
Sudheer Shanka817b9112018-12-13 17:40:28 -08001114 return remountUidLegacy(uid, mountMode);
1115 }
1116
1117 appid_t appId = multiuser_get_app_id(uid);
1118 userid_t userId = multiuser_get_user_id(uid);
1119 std::vector<std::string> visibleVolLabels;
1120 for (auto& volId : mVisibleVolumeIds) {
1121 auto vol = findVolume(volId);
1122 userid_t mountUserId = vol->getMountUserId();
1123 if (mountUserId == userId || vol->isEmulated()) {
1124 visibleVolLabels.push_back(vol->getLabel());
1125 }
1126 }
1127
1128 // Finding one package with appId is enough
1129 std::vector<std::string> packageNames;
1130 for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
1131 if (it->second == appId) {
1132 packageNames.push_back(it->first);
1133 break;
1134 }
1135 }
1136 if (packageNames.empty()) {
1137 PLOG(ERROR) << "Failed to find packageName for " << uid;
Sudheer Shanka53947a32018-08-01 10:24:13 -07001138 return -1;
1139 }
Sudheer Shanka817b9112018-12-13 17:40:28 -08001140 return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
1141}
1142
1143int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
1144 std::string mode;
1145 switch (mountMode) {
1146 case VoldNativeService::REMOUNT_MODE_NONE:
1147 mode = "none";
1148 break;
1149 case VoldNativeService::REMOUNT_MODE_DEFAULT:
1150 mode = "default";
1151 break;
1152 case VoldNativeService::REMOUNT_MODE_READ:
1153 mode = "read";
1154 break;
1155 case VoldNativeService::REMOUNT_MODE_WRITE:
1156 mode = "write";
1157 break;
1158 default:
1159 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
1160 return -1;
1161 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001162 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1163
1164 DIR* dir;
1165 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001166 std::string rootName;
1167 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001168 int pidFd;
1169 int nsFd;
1170 struct stat sb;
1171 pid_t child;
1172
1173 if (!(dir = opendir("/proc"))) {
1174 PLOG(ERROR) << "Failed to opendir";
1175 return -1;
1176 }
1177
1178 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001179 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1180 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001181 closedir(dir);
1182 return -1;
1183 }
1184
1185 // Poke through all running PIDs look for apps running as UID
1186 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001187 pid_t pid;
1188 if (de->d_type != DT_DIR) continue;
1189 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1190
Jeff Sharkey66270a22015-06-24 11:49:24 -07001191 pidFd = -1;
1192 nsFd = -1;
1193
1194 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1195 if (pidFd < 0) {
1196 goto next;
1197 }
1198 if (fstat(pidFd, &sb) != 0) {
1199 PLOG(WARNING) << "Failed to stat " << de->d_name;
1200 goto next;
1201 }
1202 if (sb.st_uid != uid) {
1203 goto next;
1204 }
1205
1206 // Matches so far, but refuse to touch if in root namespace
1207 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001208 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001209 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1210 goto next;
1211 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001212 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001213 LOG(WARNING) << "Skipping due to root namespace";
1214 goto next;
1215 }
1216
1217 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001218 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -07001219 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001220 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001221 goto next;
1222 }
1223
1224 if (!(child = fork())) {
1225 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001226 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001227 _exit(1);
1228 }
1229
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001230 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001231
1232 std::string storageSource;
1233 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001234 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001235 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001236 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001237 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001238 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001239 } else {
1240 // Sane default of no storage visible
1241 _exit(0);
1242 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001243 if (TEMP_FAILURE_RETRY(
1244 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1245 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001246 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001247 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001248 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1249 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001250 _exit(1);
1251 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001252
1253 // Mount user-specific symlink helper into place
1254 userid_t user_id = multiuser_get_user_id(uid);
1255 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001256 if (TEMP_FAILURE_RETRY(
1257 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1258 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001259 _exit(1);
1260 }
1261
Jeff Sharkey66270a22015-06-24 11:49:24 -07001262 _exit(0);
1263 }
1264
1265 if (child == -1) {
1266 PLOG(ERROR) << "Failed to fork";
1267 goto next;
1268 } else {
1269 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1270 }
1271
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001272 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001273 close(nsFd);
1274 close(pidFd);
1275 }
1276 closedir(dir);
1277 return 0;
1278}
1279
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001280int VolumeManager::reset() {
1281 // Tear down all existing disks/volumes and start from a blank slate so
1282 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001283 if (mInternalEmulated != nullptr) {
1284 mInternalEmulated->destroy();
1285 mInternalEmulated->create();
1286 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001287 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001288 disk->destroy();
1289 disk->create();
1290 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001291 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001292 mAddedUsers.clear();
1293 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001294
1295 mUserPackages.clear();
1296 mAppIds.clear();
1297 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001298 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001299
1300 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001301 android::vold::UnmountTreeWithPrefix("/mnt/user/");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001302 return 0;
1303}
1304
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001305// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001306int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001307 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001308 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001309 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001310 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001311 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001312 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001313 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001314 disk->destroy();
1315 }
Risan8c9f3322018-10-29 08:52:56 +09001316 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001317 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001318 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001319 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001320 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001321}
1322
Jeff Sharkey9c484982015-03-31 10:35:33 -07001323int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001324 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001325 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001326
Jeff Sharkey9c484982015-03-31 10:35:33 -07001327 // First, try gracefully unmounting all known devices
1328 if (mInternalEmulated != nullptr) {
1329 mInternalEmulated->unmount();
1330 }
Risan8c9f3322018-10-29 08:52:56 +09001331 for (const auto& stub : mStubVolumes) {
1332 stub->unmount();
1333 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001334 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001335 disk->unmountAll();
1336 }
1337
1338 // Worst case we might have some stale mounts lurking around, so
1339 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001340 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001341 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001342 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001343 return -errno;
1344 }
1345
1346 // Some volumes can be stacked on each other, so force unmount in
1347 // reverse order to give us the best chance of success.
1348 std::list<std::string> toUnmount;
1349 mntent* mentry;
1350 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001351 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001352 if ((StartsWith(test, "/mnt/") &&
1353#ifdef __ANDROID_DEBUGGABLE__
1354 !StartsWith(test, "/mnt/scratch") &&
1355#endif
1356 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1357 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001358 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001359 }
1360 }
1361 endmntent(fp);
1362
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001363 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001364 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001365 android::vold::ForceUnmount(path);
1366 }
1367
1368 return 0;
1369}
1370
Jeff Sharkey3472e522017-10-06 18:02:53 -06001371int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001372 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001373 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001374 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001375 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001376 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001377 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001378 return -EINVAL;
1379 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001380}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001381
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001382int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001383 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001384 int id = mNextObbId++;
1385
1386 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001387 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001388 vol->create();
1389
1390 mObbVolumes.push_back(vol);
1391 *outVolId = vol->getId();
1392 return android::OK;
1393}
1394
1395int VolumeManager::destroyObb(const std::string& volId) {
1396 auto i = mObbVolumes.begin();
1397 while (i != mObbVolumes.end()) {
1398 if ((*i)->getId() == volId) {
1399 (*i)->destroy();
1400 i = mObbVolumes.erase(i);
1401 } else {
1402 ++i;
1403 }
1404 }
1405 return android::OK;
1406}
1407
Risan8c9f3322018-10-29 08:52:56 +09001408int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1409 const std::string& fsType, const std::string& fsUuid,
1410 const std::string& fsLabel, std::string* outVolId) {
1411 int id = mNextStubVolumeId++;
1412 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1413 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1414 vol->create();
1415
1416 mStubVolumes.push_back(vol);
1417 *outVolId = vol->getId();
1418 return android::OK;
1419}
1420
1421int VolumeManager::destroyStubVolume(const std::string& volId) {
1422 auto i = mStubVolumes.begin();
1423 while (i != mStubVolumes.end()) {
1424 if ((*i)->getId() == volId) {
1425 (*i)->destroy();
1426 i = mStubVolumes.erase(i);
1427 } else {
1428 ++i;
1429 }
1430 }
1431 return android::OK;
1432}
1433
Risan8f6198d2018-10-26 20:56:45 -06001434int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001435 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001436}
1437
Risan8f6198d2018-10-26 20:56:45 -06001438int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001439 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001440}
1441
1442int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001443 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001444}