blob: 547c7ef49d1ab5004be51bd42e29b376aa641c58 [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 Shanka40ab6742018-09-18 13:07:45 -0700428 struct stat fullWriteSb;
429 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &fullWriteSb)) == -1) {
430 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
431 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700432 }
433
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700434 std::unordered_set<appid_t> validAppIds;
435 for (auto& package : packageNames) {
436 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700437 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700438 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700439
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700440 struct dirent* de;
441 // Poke through all running PIDs look for apps running in userId
442 while ((de = readdir(dirp.get()))) {
443 pid_t pid;
444 if (de->d_type != DT_DIR) continue;
445 if (!android::base::ParseInt(de->d_name, &pid)) continue;
446
447 const unique_fd pidFd(
448 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
449 if (pidFd.get() < 0) {
450 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700451 continue;
452 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700453 struct stat sb;
454 if (fstat(pidFd.get(), &sb) != 0) {
455 PLOG(WARNING) << "Failed to stat " << de->d_name;
456 continue;
457 }
458 if (multiuser_get_user_id(sb.st_uid) != userId) {
459 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700460 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700461
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700462 // Matches so far, but refuse to touch if in root namespace
463 LOG(VERBOSE) << "Found matching PID " << de->d_name;
464 std::string pidName;
465 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
466 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
467 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700468 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700469 if (rootName == pidName) {
470 LOG(WARNING) << "Skipping due to root namespace";
471 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700472 }
473
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700474 // Only update the mount points of processes running with one of validAppIds.
475 // This should skip any isolated uids.
476 appid_t appId = multiuser_get_app_id(sb.st_uid);
477 if (validAppIds.find(appId) == validAppIds.end()) {
478 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700479 }
480
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700481 std::vector<std::string> packagesForUid;
482 for (auto& package : userPackages) {
483 if (mAppIds[package] == appId) {
484 packagesForUid.push_back(package);
485 }
486 }
487 if (packagesForUid.empty()) {
488 continue;
489 }
490 const std::string& sandboxId = mSandboxIds[appId];
491
492 // We purposefully leave the namespace open across the fork
493 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
494 if (nsFd.get() < 0) {
495 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
496 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700497 }
498
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700499 pid_t child;
500 if (!(child = fork())) {
501 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
502 PLOG(ERROR) << "Failed to setns for " << de->d_name;
503 _exit(1);
504 }
505
Sudheer Shanka817b9112018-12-13 17:40:28 -0800506 int mountMode;
507 if (remountMode == -1) {
508 mountMode = getMountModeForRunningProc(packagesForUid, userId, fullWriteSb);
509 if (mountMode == -1) {
510 _exit(1);
511 }
512 } else {
513 mountMode = remountMode;
514 std::string obbMountFile = StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId,
515 packagesForUid[0].c_str());
516 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
517 if (access(obbMountFile.c_str(), F_OK) != 0) {
518 const unique_fd fd(
519 TEMP_FAILURE_RETRY(open(obbMountFile.c_str(), O_RDWR | O_CREAT, 0660)));
520 }
521 } else {
522 if (access(obbMountFile.c_str(), F_OK) == 0) {
523 remove(obbMountFile.c_str());
524 }
525 }
526 }
527 if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
528 mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
529 // These mount modes are not going to change dynamically, so don't bother
530 // unmounting/remounting dirs.
531 _exit(0);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700532 }
533
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700534 for (auto& volumeLabel : visibleVolLabels) {
535 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
536 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
537 if (volumeLabel == "emulated") {
538 StringAppendF(&mntSource, "/%d", userId);
539 StringAppendF(&mntTarget, "/%d", userId);
540 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800541 std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
542 std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
543 if (umount2(obbTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
544 errno != ENOENT) {
545 PLOG(ERROR) << "Failed to unmount " << obbTargetDir;
546 continue;
547 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700548 for (auto& package : packagesForUid) {
549 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
550 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
Sudheer Shanka03992e32018-12-12 12:43:38 -0800551 if (mountMode != VoldNativeService::REMOUNT_MODE_INSTALLER) {
552 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
553 }
554 }
555 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800556 if (TEMP_FAILURE_RETRY(mount(obbSourceDir.c_str(), obbTargetDir.c_str(),
557 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
558 PLOG(ERROR) << "Failed to mount " << obbSourceDir << " to " << obbTargetDir;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800559 continue;
560 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800561 if (TEMP_FAILURE_RETRY(mount(nullptr, obbTargetDir.c_str(), nullptr,
Sudheer Shanka03992e32018-12-12 12:43:38 -0800562 MS_REC | MS_SLAVE, nullptr)) == -1) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800563 PLOG(ERROR) << "Failed to set MS_SLAVE at " << obbTargetDir.c_str();
Sudheer Shanka03992e32018-12-12 12:43:38 -0800564 continue;
565 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700566 }
567 }
568 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700569 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700570
571 if (child == -1) {
572 PLOG(ERROR) << "Failed to fork";
573 } else {
574 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700575 }
576 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700577 return 0;
578}
579
Sudheer Shanka03992e32018-12-12 12:43:38 -0800580int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
581 userid_t userId, struct stat& mntWriteStat) {
582 struct stat storageSb;
583 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
584 PLOG(ERROR) << "Failed to stat /storage";
585 return -1;
586 }
587
588 // Some packages have access to full external storage, identify processes belonging
589 // to those packages by comparing inode no.s of /mnt/runtime/write and /storage
590 if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
591 return VoldNativeService::REMOUNT_MODE_FULL;
592 }
593
594 std::string obbMountFile =
595 StringPrintf("/mnt/user/%d/package/%s/obb_mount", userId, packagesForUid[0].c_str());
596 if (access(obbMountFile.c_str(), F_OK) == 0) {
597 return VoldNativeService::REMOUNT_MODE_INSTALLER;
598 }
599
600 // Some packages don't have access to external storage and processes belonging to
601 // those packages don't have anything mounted at /storage. So, identify those
602 // processes by comparing inode no.s of /mnt/user/%d/package/%s
603 // and /storage
604 for (auto& package : packagesForUid) {
605 std::string sandbox = StringPrintf("/mnt/user/%d/package/%s", userId, package.c_str());
606 struct stat sandboxStat;
607 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
608 PLOG(ERROR) << "Failed to stat " << sandbox;
609 return -1;
610 }
611 if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
612 return VoldNativeService::REMOUNT_MODE_WRITE;
613 }
614 }
615 return VoldNativeService::REMOUNT_MODE_NONE;
616}
617
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700618int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
619 const std::vector<std::string>& visibleVolLabels) {
620 if (visibleVolLabels.empty()) {
621 return 0;
622 }
623 for (auto& volumeLabel : visibleVolLabels) {
624 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
625 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
626 if (isVolPrimaryEmulated) {
627 StringAppendF(&volumeRoot, "/%d", userId);
628 if (fs_prepare_dir(volumeRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
629 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeRoot;
630 return -errno;
631 }
632 }
633
634 std::string sandboxRoot =
635 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
636 if (sandboxRoot.empty()) {
637 return -errno;
638 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700639
640 if (!createPkgSpecificDirRoots(volumeRoot)) {
641 return -errno;
642 }
643
644 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
645 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
646 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
647 return -errno;
648 }
649 mntTargetRoot.append("/package");
650 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
651 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
652 return -errno;
653 }
654
655 for (auto& packageName : packageNames) {
656 const auto& it = mAppIds.find(packageName);
657 if (it == mAppIds.end()) {
658 PLOG(ERROR) << "appId is not available for " << packageName;
659 continue;
660 }
661 appid_t appId = it->second;
662 std::string sandboxId = mSandboxIds[appId];
663 uid_t uid = multiuser_get_uid(userId, appId);
664
665 // [1] Create /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
666 // [2] Create /mnt/user/0/package/<packageName>/emulated/0
667 // Mount [1] at [2]
668 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
669 if (pkgSandboxSourceDir.empty()) {
670 return -errno;
671 }
672 std::string pkgSandboxTargetDir = prepareSandboxTarget(
673 packageName, uid, volumeLabel, mntTargetRoot, isVolPrimaryEmulated);
674 if (pkgSandboxTargetDir.empty()) {
675 return -errno;
676 }
677 if (umount2(pkgSandboxTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
678 errno != ENOENT) {
679 PLOG(ERROR) << "Failed to unmount " << pkgSandboxTargetDir;
680 return -errno;
681 }
682 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
683 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
684 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
685 << pkgSandboxTargetDir;
686 return -errno;
687 }
688 if (TEMP_FAILURE_RETRY(mount(nullptr, pkgSandboxTargetDir.c_str(), nullptr,
689 MS_SLAVE | MS_REC, nullptr)) == -1) {
690 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
691 << pkgSandboxTargetDir;
692 return -errno;
693 }
694
695 // Create Android/{data,media,obb}/<packageName> segments at
696 // [1] /mnt/runtime/write/emulated/0/ and
697 // [2] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>/emulated/0/
698 if (!createPkgSpecificDirs(packageName, uid, volumeRoot, pkgSandboxSourceDir)) {
699 return -errno;
700 }
701
702 if (volumeLabel == mPrimary->getLabel()) {
703 // Create [1] /mnt/user/0/package/<packageName>/self/
704 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
705 // Mount [2] at [1]
706 std::string pkgPrimaryTargetDir =
707 StringPrintf("%s/%s/self", mntTargetRoot.c_str(), packageName.c_str());
708 if (fs_prepare_dir(pkgPrimaryTargetDir.c_str(), 0755, uid, uid) != 0) {
709 PLOG(ERROR) << "Failed to fs_prepare_dir on " << pkgPrimaryTargetDir;
710 return -errno;
711 }
712 StringAppendF(&pkgPrimaryTargetDir, "/primary");
713 std::string primarySource(mPrimary->getPath());
714 if (isVolPrimaryEmulated) {
715 StringAppendF(&primarySource, "/%d", userId);
716 }
717 if (TEMP_FAILURE_RETRY(unlink(pkgPrimaryTargetDir.c_str()))) {
718 if (errno != ENOENT) {
719 PLOG(ERROR) << "Failed to unlink " << pkgPrimaryTargetDir;
720 }
721 }
722 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), pkgPrimaryTargetDir.c_str()))) {
723 PLOG(ERROR) << "Failed to link " << primarySource << " at "
724 << pkgPrimaryTargetDir;
725 return -errno;
726 }
727 }
728 }
729 }
Sudheer Shanka817b9112018-12-13 17:40:28 -0800730 mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700731 return 0;
732}
733
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700734std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
735 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700736 std::string path(pathPrefix);
737 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
738 for (size_t i = 0; i < subDirList.size(); ++i) {
739 std::string subDir = subDirList[i];
740 if (subDir.empty()) {
741 continue;
742 }
743 StringAppendF(&path, "/%s", subDir.c_str());
744 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
745 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
746 return kEmptyString;
747 }
748 }
749 return path;
750}
751
752std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700753 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700754 std::string sandboxSourceDir(sandboxRootDir);
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700755 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700756 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
757 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
758 return kEmptyString;
759 }
760 return sandboxSourceDir;
761}
762
763std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700764 const std::string& volumeLabel,
765 const std::string& mntTargetRootDir,
766 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700767 std::string segment;
768 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700769 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
770 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700771 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700772 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700773 }
774 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
775}
776
777std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700778 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700779 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
780 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
781 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
782 return kEmptyString;
783 }
784 return dataSourceDir;
785}
786
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700787bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
788 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
789 if (fs_prepare_dir(volumeAndroidRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
790 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeAndroidRoot;
791 return false;
792 }
793 std::array<std::string, 3> dirs = {"data", "media", "obb"};
794 for (auto& dir : dirs) {
795 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
796 if (fs_prepare_dir(path.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
797 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
798 return false;
799 }
800 }
801 return true;
802}
803
804bool VolumeManager::createPkgSpecificDirs(const std::string& packageName, uid_t uid,
805 const std::string& volumeRoot,
806 const std::string& sandboxDirRoot) {
807 std::array<std::string, 3> dirs = {"data", "media", "obb"};
808 for (auto& dir : dirs) {
809 std::string sourceDir = StringPrintf("%s/Android/%s", volumeRoot.c_str(), dir.c_str());
810 if (prepareSubDirs(sourceDir, packageName, 0755, uid, uid).empty()) {
811 return false;
812 }
813 std::string sandboxSegment =
814 StringPrintf("Android/%s/%s/", dir.c_str(), packageName.c_str());
815 if (prepareSubDirs(sandboxDirRoot, sandboxSegment, 0755, uid, uid).empty()) {
816 return false;
817 }
818 }
819 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700820}
821
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700822int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
823 mAddedUsers[userId] = userSerialNumber;
824 return 0;
825}
826
827int VolumeManager::onUserRemoved(userid_t userId) {
828 mAddedUsers.erase(userId);
829 return 0;
830}
831
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700832int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
833 const std::vector<int>& appIds,
834 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700835 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700836 // Note that sometimes the system will spin up processes from Zygote
837 // before actually starting the user, so we're okay if Zygote
838 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600839 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700840 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
841
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700842 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700843 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700844 for (size_t i = 0; i < packageNames.size(); ++i) {
845 mAppIds[packageNames[i]] = appIds[i];
846 mSandboxIds[appIds[i]] = sandboxIds[i];
847 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700848 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700849 linkPrimary(userId);
850 }
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800851 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700852 std::vector<std::string> visibleVolLabels;
853 for (auto& volId : mVisibleVolumeIds) {
854 auto vol = findVolume(volId);
855 userid_t mountUserId = vol->getMountUserId();
856 if (mountUserId == userId || vol->isEmulated()) {
857 visibleVolLabels.push_back(vol->getLabel());
858 }
859 }
860 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
861 return -errno;
862 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700863 }
864 return 0;
865}
866
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700867int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700868 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700869 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700870
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800871 if (hasIsolatedStorage()) {
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700872 mUserPackages.erase(userId);
873 std::string mntTargetDir = StringPrintf("/mnt/user/%d", userId);
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800874 if (android::vold::UnmountTreeWithPrefix(mntTargetDir) < 0) {
875 PLOG(ERROR) << "UnmountTreeWithPrefix on " << mntTargetDir << " failed";
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700876 return -errno;
877 }
878 if (android::vold::DeleteDirContentsAndDir(mntTargetDir) < 0) {
879 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << mntTargetDir;
880 return -errno;
881 }
882 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << mntTargetDir;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700883 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700884 return 0;
885}
886
Sudheer Shankad484aa92018-07-31 10:07:34 -0700887int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700888 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700889 for (size_t i = 0; i < packageNames.size(); ++i) {
890 mAppIds[packageNames[i]] = appIds[i];
891 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700892 return 0;
893}
894
895int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700896 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700897 for (size_t i = 0; i < appIds.size(); ++i) {
898 mSandboxIds[appIds[i]] = sandboxIds[i];
899 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700900 return 0;
901}
902
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700903int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
904 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800905 if (!hasIsolatedStorage()) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700906 return 0;
907 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
908 // User not started, no need to do anything now. Required bind mounts for the package will
909 // be created when the user starts.
910 return 0;
911 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700912 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700913 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700914 mUserPackages[userId].push_back(packageName);
915 mAppIds[packageName] = appId;
916 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700917
918 std::vector<std::string> visibleVolLabels;
919 for (auto& volId : mVisibleVolumeIds) {
920 auto vol = findVolume(volId);
921 userid_t mountUserId = vol->getMountUserId();
922 if (mountUserId == userId || vol->isEmulated()) {
923 visibleVolLabels.push_back(vol->getLabel());
924 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700925 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700926 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700927}
928
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700929int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700930 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800931 if (!hasIsolatedStorage()) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700932 return 0;
933 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700934 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
935 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700936 auto& userPackages = mUserPackages[userId];
Sudheer Shankaba0c62f2018-12-16 18:22:34 -0800937 userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
938 userPackages.end());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700939 // If the package is not uninstalled in any other users, remove appId and sandboxId
940 // corresponding to it from the internal state.
941 bool installedInAnyUser = false;
942 for (auto& it : mUserPackages) {
943 auto& packages = it.second;
944 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
945 installedInAnyUser = true;
946 break;
947 }
948 }
949 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700950 const auto& entry = mAppIds.find(packageName);
951 if (entry != mAppIds.end()) {
952 mSandboxIds.erase(entry->second);
953 mAppIds.erase(entry);
954 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700955 }
956
957 std::vector<std::string> visibleVolLabels;
958 for (auto& volId : mVisibleVolumeIds) {
959 auto vol = findVolume(volId);
960 userid_t mountUserId = vol->getMountUserId();
961 if (mountUserId == userId || vol->isEmulated()) {
962 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
963 return -errno;
964 }
965 }
966 }
967 return 0;
968}
969
970int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
971 const std::string& sandboxId, userid_t userId,
972 const std::string& volLabel) {
973 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
974 << ", volLabel=" << volLabel;
975 std::string pkgSandboxTarget =
976 StringPrintf("/mnt/user/%d/package/%s", userId, packageName.c_str());
Sudheer Shanka6bf14802019-01-17 13:38:10 -0800977 if (android::vold::UnmountTreeWithPrefix(pkgSandboxTarget) < 0) {
978 PLOG(ERROR) << "UnmountTreeWithPrefix failed on " << pkgSandboxTarget;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700979 }
980
981 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
982 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
983 StringAppendF(&sandboxDir, "/%d", userId);
984 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700985 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700986
987 if (android::vold::DeleteDirContentsAndDir(sandboxDir) < 0) {
988 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
989 return -errno;
990 }
991 return 0;
992}
993
Jeff Sharkey401b2602017-12-14 22:15:20 -0700994int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
995 mSecureKeyguardShowing = isShowing;
996 if (!mSecureKeyguardShowing) {
997 // Now that secure keyguard has been dismissed, process
998 // any pending disks
999 for (const auto& disk : mPendingDisks) {
1000 disk->create();
1001 mDisks.push_back(disk);
1002 }
1003 mPendingDisks.clear();
1004 }
1005 return 0;
1006}
1007
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001008int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001009 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001010 return 0;
1011 }
1012
1013 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
1014 return 0;
1015 }
1016
1017 mVisibleVolumeIds.insert(vol->getId());
1018 userid_t mountUserId = vol->getMountUserId();
1019 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1020 // We don't want to create another shared_ptr here because then we will end up with
1021 // two shared_ptrs owning the underlying pointer without sharing it.
1022 mPrimary = findVolume(vol->getId());
1023 for (userid_t userId : mStartedUsers) {
1024 if (linkPrimary(userId) != 0) {
1025 return -errno;
1026 }
1027 }
1028 }
1029 if (vol->isEmulated()) {
1030 for (userid_t userId : mStartedUsers) {
1031 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
1032 return -errno;
1033 }
1034 }
1035 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1036 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
1037 return -errno;
1038 }
1039 }
1040 return 0;
1041}
1042
1043int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001044 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001045 return 0;
1046 }
1047
1048 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
1049 return 0;
1050 }
1051
1052 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1053 mPrimary = nullptr;
1054 }
1055
1056 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
1057 userid_t mountUserId = vol->getMountUserId();
1058 if (vol->isEmulated()) {
1059 for (userid_t userId : mStartedUsers) {
1060 if (destroySandboxesForVol(vol, userId) != 0) {
1061 return -errno;
1062 }
1063 }
1064 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1065 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1066 return -errno;
1067 }
1068 }
1069 return 0;
1070}
1071
1072int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1073 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
1074 const std::vector<std::string>& packageNames = mUserPackages[userId];
1075 for (auto& packageName : packageNames) {
1076 std::string volSandboxRoot = StringPrintf("/mnt/user/%d/package/%s/%s", userId,
1077 packageName.c_str(), vol->getLabel().c_str());
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001078 if (android::vold::UnmountTreeWithPrefix(volSandboxRoot) < 0) {
1079 PLOG(ERROR) << "UnmountTreeWithPrefix on " << volSandboxRoot << " failed";
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001080 continue;
1081 }
1082 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1083 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1084 continue;
1085 }
1086 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
1087 }
1088 return 0;
1089}
1090
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001091int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001092 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001093 return 0;
1094 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001095 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001096 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001097 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001098 }
1099 return 0;
1100}
1101
Sudheer Shanka817b9112018-12-13 17:40:28 -08001102int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001103 if (!hasIsolatedStorage()) {
Sudheer Shanka817b9112018-12-13 17:40:28 -08001104 return remountUidLegacy(uid, mountMode);
1105 }
1106
1107 appid_t appId = multiuser_get_app_id(uid);
1108 userid_t userId = multiuser_get_user_id(uid);
1109 std::vector<std::string> visibleVolLabels;
1110 for (auto& volId : mVisibleVolumeIds) {
1111 auto vol = findVolume(volId);
1112 userid_t mountUserId = vol->getMountUserId();
1113 if (mountUserId == userId || vol->isEmulated()) {
1114 visibleVolLabels.push_back(vol->getLabel());
1115 }
1116 }
1117
1118 // Finding one package with appId is enough
1119 std::vector<std::string> packageNames;
1120 for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
1121 if (it->second == appId) {
1122 packageNames.push_back(it->first);
1123 break;
1124 }
1125 }
1126 if (packageNames.empty()) {
1127 PLOG(ERROR) << "Failed to find packageName for " << uid;
Sudheer Shanka53947a32018-08-01 10:24:13 -07001128 return -1;
1129 }
Sudheer Shanka817b9112018-12-13 17:40:28 -08001130 return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
1131}
1132
1133int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
1134 std::string mode;
1135 switch (mountMode) {
1136 case VoldNativeService::REMOUNT_MODE_NONE:
1137 mode = "none";
1138 break;
1139 case VoldNativeService::REMOUNT_MODE_DEFAULT:
1140 mode = "default";
1141 break;
1142 case VoldNativeService::REMOUNT_MODE_READ:
1143 mode = "read";
1144 break;
1145 case VoldNativeService::REMOUNT_MODE_WRITE:
1146 mode = "write";
1147 break;
1148 default:
1149 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
1150 return -1;
1151 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001152 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1153
1154 DIR* dir;
1155 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001156 std::string rootName;
1157 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001158 int pidFd;
1159 int nsFd;
1160 struct stat sb;
1161 pid_t child;
1162
1163 if (!(dir = opendir("/proc"))) {
1164 PLOG(ERROR) << "Failed to opendir";
1165 return -1;
1166 }
1167
1168 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001169 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1170 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001171 closedir(dir);
1172 return -1;
1173 }
1174
1175 // Poke through all running PIDs look for apps running as UID
1176 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001177 pid_t pid;
1178 if (de->d_type != DT_DIR) continue;
1179 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1180
Jeff Sharkey66270a22015-06-24 11:49:24 -07001181 pidFd = -1;
1182 nsFd = -1;
1183
1184 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1185 if (pidFd < 0) {
1186 goto next;
1187 }
1188 if (fstat(pidFd, &sb) != 0) {
1189 PLOG(WARNING) << "Failed to stat " << de->d_name;
1190 goto next;
1191 }
1192 if (sb.st_uid != uid) {
1193 goto next;
1194 }
1195
1196 // Matches so far, but refuse to touch if in root namespace
1197 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001198 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001199 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1200 goto next;
1201 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001202 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001203 LOG(WARNING) << "Skipping due to root namespace";
1204 goto next;
1205 }
1206
1207 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001208 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -07001209 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001210 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001211 goto next;
1212 }
1213
1214 if (!(child = fork())) {
1215 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001216 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001217 _exit(1);
1218 }
1219
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001220 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001221
1222 std::string storageSource;
1223 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001224 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001225 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001226 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001227 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001228 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001229 } else {
1230 // Sane default of no storage visible
1231 _exit(0);
1232 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001233 if (TEMP_FAILURE_RETRY(
1234 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1235 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001236 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001237 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001238 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1239 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001240 _exit(1);
1241 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001242
1243 // Mount user-specific symlink helper into place
1244 userid_t user_id = multiuser_get_user_id(uid);
1245 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001246 if (TEMP_FAILURE_RETRY(
1247 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1248 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001249 _exit(1);
1250 }
1251
Jeff Sharkey66270a22015-06-24 11:49:24 -07001252 _exit(0);
1253 }
1254
1255 if (child == -1) {
1256 PLOG(ERROR) << "Failed to fork";
1257 goto next;
1258 } else {
1259 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1260 }
1261
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001262 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001263 close(nsFd);
1264 close(pidFd);
1265 }
1266 closedir(dir);
1267 return 0;
1268}
1269
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001270int VolumeManager::reset() {
1271 // Tear down all existing disks/volumes and start from a blank slate so
1272 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001273 if (mInternalEmulated != nullptr) {
1274 mInternalEmulated->destroy();
1275 mInternalEmulated->create();
1276 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001277 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001278 disk->destroy();
1279 disk->create();
1280 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001281 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001282 mAddedUsers.clear();
1283 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001284
1285 mUserPackages.clear();
1286 mAppIds.clear();
1287 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001288 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001289
1290 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
Sudheer Shanka6bf14802019-01-17 13:38:10 -08001291 android::vold::UnmountTreeWithPrefix("/mnt/user/");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001292 return 0;
1293}
1294
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001295// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001296int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001297 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001298 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001299 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001300 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001301 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001302 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001303 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001304 disk->destroy();
1305 }
Risan8c9f3322018-10-29 08:52:56 +09001306 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001307 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001308 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001309 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001310 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001311}
1312
Jeff Sharkey9c484982015-03-31 10:35:33 -07001313int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001314 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001315 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001316
Jeff Sharkey9c484982015-03-31 10:35:33 -07001317 // First, try gracefully unmounting all known devices
1318 if (mInternalEmulated != nullptr) {
1319 mInternalEmulated->unmount();
1320 }
Risan8c9f3322018-10-29 08:52:56 +09001321 for (const auto& stub : mStubVolumes) {
1322 stub->unmount();
1323 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001324 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001325 disk->unmountAll();
1326 }
1327
1328 // Worst case we might have some stale mounts lurking around, so
1329 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001330 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001331 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001332 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001333 return -errno;
1334 }
1335
1336 // Some volumes can be stacked on each other, so force unmount in
1337 // reverse order to give us the best chance of success.
1338 std::list<std::string> toUnmount;
1339 mntent* mentry;
1340 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001341 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001342 if ((StartsWith(test, "/mnt/") &&
1343#ifdef __ANDROID_DEBUGGABLE__
1344 !StartsWith(test, "/mnt/scratch") &&
1345#endif
1346 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1347 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001348 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001349 }
1350 }
1351 endmntent(fp);
1352
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001353 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001354 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001355 android::vold::ForceUnmount(path);
1356 }
1357
1358 return 0;
1359}
1360
Jeff Sharkey3472e522017-10-06 18:02:53 -06001361int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001362 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001363 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001364 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001365 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001366 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001367 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001368 return -EINVAL;
1369 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001370}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001371
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001372int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001373 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001374 int id = mNextObbId++;
1375
1376 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001377 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001378 vol->create();
1379
1380 mObbVolumes.push_back(vol);
1381 *outVolId = vol->getId();
1382 return android::OK;
1383}
1384
1385int VolumeManager::destroyObb(const std::string& volId) {
1386 auto i = mObbVolumes.begin();
1387 while (i != mObbVolumes.end()) {
1388 if ((*i)->getId() == volId) {
1389 (*i)->destroy();
1390 i = mObbVolumes.erase(i);
1391 } else {
1392 ++i;
1393 }
1394 }
1395 return android::OK;
1396}
1397
Risan8c9f3322018-10-29 08:52:56 +09001398int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1399 const std::string& fsType, const std::string& fsUuid,
1400 const std::string& fsLabel, std::string* outVolId) {
1401 int id = mNextStubVolumeId++;
1402 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1403 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1404 vol->create();
1405
1406 mStubVolumes.push_back(vol);
1407 *outVolId = vol->getId();
1408 return android::OK;
1409}
1410
1411int VolumeManager::destroyStubVolume(const std::string& volId) {
1412 auto i = mStubVolumes.begin();
1413 while (i != mStubVolumes.end()) {
1414 if ((*i)->getId() == volId) {
1415 (*i)->destroy();
1416 i = mStubVolumes.erase(i);
1417 } else {
1418 ++i;
1419 }
1420 }
1421 return android::OK;
1422}
1423
Risan8f6198d2018-10-26 20:56:45 -06001424int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001425 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001426}
1427
Risan8f6198d2018-10-26 20:56:45 -06001428int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001429 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001430}
1431
1432int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001433 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001434}