blob: 5e012c7f44db140122a223a2d84aee030bbfc5a9 [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>
29#include <sys/types.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070030#include <sys/sysmacros.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
San Mehata19b2502010-01-06 10:33:53 -080033
San Mehata2677e42009-12-13 10:40:18 -080034#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070035
Elliott Hughes7e128fb2015-12-04 15:50:53 -080036#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070037#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060038#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/strings.h>
41
Jeff Sharkey71ebe152013-09-17 17:24:38 -070042#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060043#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070044
Robert Craigb9e3ba52014-02-04 10:53:00 -050045#include <selinux/android.h>
46
San Mehatfd7f5872009-10-12 11:32:47 -070047#include <sysutils/NetlinkEvent.h>
48
Kenny Root344ca102012-04-03 17:23:01 -070049#include <private/android_filesystem_config.h>
50
Paul Crowleyc6433a22017-10-24 14:54:43 -070051#include <ext4_utils/ext4_crypt.h>
52
53#include "Devmapper.h"
54#include "Ext4Crypt.h"
San Mehata19b2502010-01-06 10:33:53 -080055#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070056#include "NetlinkManager.h"
57#include "Process.h"
58#include "Utils.h"
59#include "VoldUtil.h"
60#include "VolumeManager.h"
61#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070062#include "fs/Ext4.h"
63#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070064#include "model/EmulatedVolume.h"
65#include "model/ObbVolume.h"
San Mehat23969932010-01-09 07:08:06 -080066
Sudheer Shanka53947a32018-08-01 10:24:13 -070067using android::base::GetBoolProperty;
68using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070069using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060070using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070071
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060072static const char* kPathUserMount = "/mnt/user";
73static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
74
Sudheer Shanka53947a32018-08-01 10:24:13 -070075static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060076static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
77
Sudheer Shanka53947a32018-08-01 10:24:13 -070078static const std::string kEmptyString("");
79
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060080/* 512MiB is large enough for testing purposes */
81static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070082
Jeff Sharkey36801cc2015-03-13 16:09:20 -070083static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080084static const unsigned int kMajorBlockExperimentalMin = 240;
85static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070086
San Mehatf1b736b2009-10-10 17:22:08 -070087VolumeManager *VolumeManager::sInstance = NULL;
88
89VolumeManager *VolumeManager::Instance() {
90 if (!sInstance)
91 sInstance = new VolumeManager();
92 return sInstance;
93}
94
95VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080096 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060097 mNextObbId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -070098 // For security reasons, assume that a secure keyguard is
99 // showing until we hear otherwise
100 mSecureKeyguardShowing = true;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700101 mMntStorageCreated = false;
San Mehatf1b736b2009-10-10 17:22:08 -0700102}
103
104VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800105}
106
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600107int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600108 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600109 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600110 if (access(kPathVirtualDisk, F_OK) != 0) {
111 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
112 }
113
114 if (mVirtualDisk == nullptr) {
115 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
116 LOG(ERROR) << "Failed to create virtual disk";
117 return -1;
118 }
119
120 struct stat buf;
121 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
122 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
123 return -1;
124 }
125
126 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
127 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600128 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700129 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600130 }
131 } else {
132 if (mVirtualDisk != nullptr) {
133 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700134 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600135
136 Loop::destroyByDevice(mVirtualDiskPath.c_str());
137 mVirtualDisk = nullptr;
138 }
139
140 if (access(kPathVirtualDisk, F_OK) == 0) {
141 unlink(kPathVirtualDisk);
142 }
143 }
144 return 0;
145}
146
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700147int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800148 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700149 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800150}
151
San Mehatf1b736b2009-10-10 17:22:08 -0700152int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600153 ATRACE_NAME("VolumeManager::start");
154
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700155 // Always start from a clean slate by unmounting everything in
156 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700157 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700158
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600159 Devmapper::destroyAll();
160 Loop::destroyAll();
161
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700162 // Assume that we always have an emulated volume on internal
163 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700164 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700165 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700166 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700167 mInternalEmulated->create();
168
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600169 // Consider creating a virtual disk
170 updateVirtualDisk();
171
San Mehatf1b736b2009-10-10 17:22:08 -0700172 return 0;
173}
174
175int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700176 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 mInternalEmulated->destroy();
178 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700179 return 0;
180}
181
San Mehatfd7f5872009-10-12 11:32:47 -0700182void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700183 std::lock_guard<std::mutex> lock(mLock);
184
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700185 if (mDebug) {
186 LOG(VERBOSE) << "----------------";
187 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
188 evt->dump();
189 }
San Mehatf1b736b2009-10-10 17:22:08 -0700190
Mateusz Nowak64403792015-08-03 16:39:19 +0200191 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
192 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700193
194 if (devType != "disk") return;
195
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600196 int major = std::stoi(evt->findParam("MAJOR"));
197 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700198 dev_t device = makedev(major, minor);
199
200 switch (evt->getAction()) {
201 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700202 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700203 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800204 // For now, assume that MMC and virtio-blk (the latter is
205 // emulator-specific; see Disk.cpp for details) devices are SD,
206 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700207 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800208 if (major == kMajorBlockMmc
209 || (android::vold::IsRunningInEmulator()
210 && major >= (int) kMajorBlockExperimentalMin
211 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700212 flags |= android::vold::Disk::Flags::kSd;
213 } else {
214 flags |= android::vold::Disk::Flags::kUsb;
215 }
216
217 auto disk = new android::vold::Disk(eventPath, device,
218 source->getNickname(), flags);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700219 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700220 break;
221 }
222 }
223 break;
224 }
225 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700226 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700227 handleDiskChanged(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700228 break;
229 }
230 case NetlinkEvent::Action::kRemove: {
Jeff Sharkey401b2602017-12-14 22:15:20 -0700231 handleDiskRemoved(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700232 break;
233 }
234 default: {
235 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
236 break;
237 }
238 }
239}
240
Jeff Sharkey401b2602017-12-14 22:15:20 -0700241void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
242 // For security reasons, if secure keyguard is showing, wait
243 // until the user unlocks the device to actually touch it
244 if (mSecureKeyguardShowing) {
245 LOG(INFO) << "Found disk at " << disk->getEventPath()
246 << " but delaying scan due to secure keyguard";
247 mPendingDisks.push_back(disk);
248 } else {
249 disk->create();
250 mDisks.push_back(disk);
251 }
252}
253
254void VolumeManager::handleDiskChanged(dev_t device) {
255 for (const auto& disk : mDisks) {
256 if (disk->getDevice() == device) {
257 disk->readMetadata();
258 disk->readPartitions();
259 }
260 }
261
262 // For security reasons, we ignore all pending disks, since
263 // we'll scan them once the device is unlocked
264}
265
266void VolumeManager::handleDiskRemoved(dev_t device) {
267 auto i = mDisks.begin();
268 while (i != mDisks.end()) {
269 if ((*i)->getDevice() == device) {
270 (*i)->destroy();
271 i = mDisks.erase(i);
272 } else {
273 ++i;
274 }
275 }
276 auto j = mPendingDisks.begin();
277 while (j != mPendingDisks.end()) {
278 if ((*j)->getDevice() == device) {
279 j = mPendingDisks.erase(j);
280 } else {
281 ++j;
282 }
283 }
284}
285
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700286void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800287 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700288 mDiskSources.push_back(diskSource);
289}
290
291std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
292 for (auto disk : mDisks) {
293 if (disk->getId() == id) {
294 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700295 }
296 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700297 return nullptr;
298}
San Mehatf1b736b2009-10-10 17:22:08 -0700299
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700300std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800301 // Vold could receive "mount" after "shutdown" command in the extreme case.
302 // If this happens, mInternalEmulated will equal nullptr and
303 // we need to deal with it in order to avoid null pointer crash.
304 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700305 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700306 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700307 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700308 auto vol = disk->findVolume(id);
309 if (vol != nullptr) {
310 return vol;
311 }
312 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600313 for (const auto& vol : mObbVolumes) {
314 if (vol->getId() == id) {
315 return vol;
316 }
317 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318 return nullptr;
319}
320
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700321void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
322 std::list<std::string>& list) {
323 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700324 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700325 disk->listVolumes(type, list);
326 }
327}
328
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600329int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700330 std::string normalizedGuid;
331 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
332 LOG(WARNING) << "Invalid GUID " << partGuid;
333 return -1;
334 }
335
Paul Crowleyc6433a22017-10-24 14:54:43 -0700336 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700337 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
338 if (unlink(keyPath.c_str()) != 0) {
339 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700340 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700341 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700342 if (e4crypt_is_native()) {
343 if (!e4crypt_destroy_volume_keys(fsUuid)) {
344 success = false;
345 }
346 }
347 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700348}
349
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700350static int prepareMntStorageDir() {
351 std::string mntTarget("/mnt/storage");
352 if (fs_prepare_dir(mntTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
353 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTarget;
354 return -errno;
355 }
356 if (TEMP_FAILURE_RETRY(mount("/mnt/runtime/write", mntTarget.c_str(),
357 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
358 PLOG(ERROR) << "Failed to mount /mnt/runtime/write at " << mntTarget;
359 return -errno;
360 }
361 if (TEMP_FAILURE_RETRY(mount(nullptr, mntTarget.c_str(),
362 nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
363 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTarget;
364 return -errno;
365 }
366 return 0;
367}
368
Sudheer Shanka53947a32018-08-01 10:24:13 -0700369int VolumeManager::linkPrimary(userid_t userId, const std::vector<std::string>& packageNames) {
370 if (GetBoolProperty(kIsolatedStorage, false)) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700371 // This should ideally go into start() but it's possible that system properties are not
372 // loaded at that point.
373 if (!mMntStorageCreated) {
374 prepareMntStorageDir();
375 mMntStorageCreated = true;
376 }
377
378 std::string source(StringPrintf("/mnt/storage/%s", mPrimary->getLabel().c_str()));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700379 bool isPrimaryEmulated =
380 (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated);
381 if (isPrimaryEmulated) {
382 StringAppendF(&source, "/%d", userId);
383 if (fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
384 PLOG(ERROR) << "fs_prepare_dir failed on " << source;
385 return -errno;
386 }
387 }
Sudheer Shankaa695f252018-08-03 18:07:52 -0700388 if (mountSandboxesForPrimaryVol(source, userId, packageNames, isPrimaryEmulated) != 0) {
389 return -errno;
390 }
391 // Keep /sdcard working for shell process
392 std::string primarySource(mPrimary->getPath());
393 if (isPrimaryEmulated) {
394 StringAppendF(&primarySource, "/%d", userId);
395 }
396 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
397 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
398 if (errno != ENOENT) {
399 PLOG(WARNING) << "Failed to unlink " << target;
400 }
401 }
402 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), target.c_str()))) {
403 PLOG(WARNING) << "Failed to link " << primarySource << " at " << target;
404 return -errno;
405 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700406 } else {
407 std::string source(mPrimary->getPath());
408 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
409 source = StringPrintf("%s/%d", source.c_str(), userId);
410 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
411 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700412
Sudheer Shanka53947a32018-08-01 10:24:13 -0700413 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
414 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
415 if (errno != ENOENT) {
416 PLOG(WARNING) << "Failed to unlink " << target;
417 }
418 }
419 LOG(DEBUG) << "Linking " << source << " to " << target;
420 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
421 PLOG(WARNING) << "Failed to link";
422 return -errno;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700423 }
424 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700425 return 0;
426}
427
428int VolumeManager::mountSandboxesForPrimaryVol(const std::string& primaryRoot, userid_t userId,
429 const std::vector<std::string>& packageNames, bool isPrimaryEmulated) {
430
431 std::string sandboxRoot = prepareSubDirs(primaryRoot, "Android/sandbox/",
432 0700, AID_ROOT, AID_ROOT);
433 if (sandboxRoot.empty()) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700434 return -errno;
435 }
Sudheer Shankaf768c272018-08-04 10:10:27 -0700436 std::string sharedSandboxRoot;
437 StringAppendF(&sharedSandboxRoot, "%s/shared", sandboxRoot.c_str());
438 // Create shared sandbox base dir for apps with sharedUserIds
439 if (fs_prepare_dir(sharedSandboxRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
440 PLOG(ERROR) << "fs_prepare_dir failed on " << sharedSandboxRoot;
441 return -errno;
442 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700443
444 std::string dataRoot = prepareSubDirs(primaryRoot, "Android/data/",
445 0700, AID_ROOT, AID_ROOT);
446 if (dataRoot.empty()) {
447 return -errno;
448 }
449
Sudheer Shankaa695f252018-08-03 18:07:52 -0700450 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
451 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
452 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
453 return -errno;
454 }
455 mntTargetRoot.append("/package");
456 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
457 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700458 return -errno;
459 }
460
461 for (auto& packageName : packageNames) {
462 const auto& it = mAppIds.find(packageName);
463 if (it == mAppIds.end()) {
464 PLOG(ERROR) << "appId is not available for " << packageName;
465 continue;
466 }
467 appid_t appId = it->second;
468 std::string sandboxId = mSandboxIds[appId];
469 uid_t uid = multiuser_get_uid(userId, appId);
470
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700471 // Create /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
Sudheer Shanka53947a32018-08-01 10:24:13 -0700472 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
473 if (pkgSandboxSourceDir.empty()) {
474 return -errno;
475 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700476
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700477 // Create [1] /mnt/storage/emulated/0/Android/data/<packageName>
478 // Create [2] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>/Android/data/<packageName>
Sudheer Shanka53947a32018-08-01 10:24:13 -0700479 // Mount [1] at [2]
480 std::string pkgDataSourceDir = preparePkgDataSource(packageName, uid, dataRoot);
481 if (pkgDataSourceDir.empty()) {
482 return -errno;
483 }
484 std::string pkgDataTargetDir = preparePkgDataTarget(packageName, uid,
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700485 pkgSandboxSourceDir);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700486 if (pkgDataTargetDir.empty()) {
487 return -errno;
488 }
489 if (TEMP_FAILURE_RETRY(mount(pkgDataSourceDir.c_str(), pkgDataTargetDir.c_str(),
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700490 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700491 PLOG(ERROR) << "Failed to mount " << pkgDataSourceDir << " at "
492 << pkgDataTargetDir;
493 return -errno;
494 }
495
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700496 // Already created [1] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
497 // Create [2] /mnt/user/0/package/<packageName>/emulated/0
498 // Mount [1] at [2]
499 std::string pkgSandboxTargetDir = prepareSandboxTarget(packageName, uid,
500 mPrimary->getLabel(), mntTargetRoot, isPrimaryEmulated);
501 if (pkgSandboxTargetDir.empty()) {
502 return -errno;
503 }
504
505 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
506 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
507 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
508 << pkgSandboxTargetDir;
509 return -errno;
510 }
511
Sudheer Shanka53947a32018-08-01 10:24:13 -0700512 // Create [1] /mnt/user/0/package/<packageName>/self/primary
513 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
514 // Mount [2] at [1]
515 std::string pkgPrimaryTargetDir = prepareSubDirs(
516 StringPrintf("%s/%s", mntTargetRoot.c_str(), packageName.c_str()),
517 "self/primary/", 0755, uid, uid);
518 if (pkgPrimaryTargetDir.empty()) {
519 return -errno;
520 }
521 if (TEMP_FAILURE_RETRY(mount(pkgSandboxTargetDir.c_str(), pkgPrimaryTargetDir.c_str(),
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700522 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700523 PLOG(ERROR) << "Failed to mount " << pkgSandboxTargetDir << " at "
524 << pkgPrimaryTargetDir;
525 return -errno;
526 }
527 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700528 return 0;
529}
530
Sudheer Shanka53947a32018-08-01 10:24:13 -0700531std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix,
532 const std::string& subDirs, mode_t mode, uid_t uid, gid_t gid) {
533 std::string path(pathPrefix);
534 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
535 for (size_t i = 0; i < subDirList.size(); ++i) {
536 std::string subDir = subDirList[i];
537 if (subDir.empty()) {
538 continue;
539 }
540 StringAppendF(&path, "/%s", subDir.c_str());
541 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
542 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
543 return kEmptyString;
544 }
545 }
546 return path;
547}
548
549std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
550 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700551 std::string sandboxSourceDir(sandboxRootDir);
552 if (android::base::StartsWith(sandboxId, "shared:")) {
553 StringAppendF(&sandboxSourceDir, "/shared/%s", sandboxId.substr(7).c_str());
554 } else {
555 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
556 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700557 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
558 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
559 return kEmptyString;
560 }
561 return sandboxSourceDir;
562}
563
564std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
565 const std::string& volumeLabel, const std::string& mntTargetRootDir,
566 bool isUserDependent) {
567 std::string segment;
568 if (isUserDependent) {
569 segment = StringPrintf("%s/%s/%d/",
570 packageName.c_str(), volumeLabel.c_str(), multiuser_get_user_id(uid));
571 } else {
572 segment = StringPrintf("%s/%s/",
573 packageName.c_str(), volumeLabel.c_str());
574 }
575 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
576}
577
578std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
579 const std::string& dataRootDir) {
580 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
581 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
582 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
583 return kEmptyString;
584 }
585 return dataSourceDir;
586}
587
588std::string VolumeManager::preparePkgDataTarget(const std::string& packageName, uid_t uid,
589 const std::string& pkgSandboxDir) {
590 std::string segment = StringPrintf("Android/data/%s/", packageName.c_str());
591 return prepareSubDirs(pkgSandboxDir, segment.c_str(), 0755, uid, uid);
592}
593
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700594int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
595 mAddedUsers[userId] = userSerialNumber;
596 return 0;
597}
598
599int VolumeManager::onUserRemoved(userid_t userId) {
600 mAddedUsers.erase(userId);
601 return 0;
602}
603
Sudheer Shankaebaad1c2018-07-31 16:39:59 -0700604int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700605 // Note that sometimes the system will spin up processes from Zygote
606 // before actually starting the user, so we're okay if Zygote
607 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600608 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700609 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
610
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700611 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700612 mUserPackages[userId] = packageNames;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700613 if (mPrimary) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700614 linkPrimary(userId, packageNames);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700615 }
616 return 0;
617}
618
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700619int VolumeManager::onUserStopped(userid_t userId) {
620 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700621 return 0;
622}
623
Sudheer Shankad484aa92018-07-31 10:07:34 -0700624int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
625 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700626 for (size_t i = 0; i < packageNames.size(); ++i) {
627 mAppIds[packageNames[i]] = appIds[i];
628 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700629 return 0;
630}
631
632int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
633 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700634 for (size_t i = 0; i < appIds.size(); ++i) {
635 mSandboxIds[appIds[i]] = sandboxIds[i];
636 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700637 return 0;
638}
639
Jeff Sharkey401b2602017-12-14 22:15:20 -0700640int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
641 mSecureKeyguardShowing = isShowing;
642 if (!mSecureKeyguardShowing) {
643 // Now that secure keyguard has been dismissed, process
644 // any pending disks
645 for (const auto& disk : mPendingDisks) {
646 disk->create();
647 mDisks.push_back(disk);
648 }
649 mPendingDisks.clear();
650 }
651 return 0;
652}
653
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700654int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
655 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700656 for (userid_t userId : mStartedUsers) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700657 linkPrimary(userId, mUserPackages[userId]);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700658 }
659 return 0;
660}
661
Jeff Sharkey3472e522017-10-06 18:02:53 -0600662static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700663 FILE* fp = setmntent("/proc/mounts", "r");
664 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600665 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700666 return -errno;
667 }
668
669 // Some volumes can be stacked on each other, so force unmount in
670 // reverse order to give us the best chance of success.
671 std::list<std::string> toUnmount;
672 mntent* mentry;
673 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600674 auto test = std::string(mentry->mnt_dir) + "/";
Elliott Hughes32a5b9a2017-12-20 12:38:47 -0800675 if (android::base::StartsWith(test, prefix)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600676 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700677 }
678 }
679 endmntent(fp);
680
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700681 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700682 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600683 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700684 }
685 }
686 return 0;
687}
688
Jeff Sharkey66270a22015-06-24 11:49:24 -0700689int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700690 // If the isolated storage is enabled, return -1 since in the isolated storage world, there
691 // are no longer any runtime storage permissions, so this shouldn't be called anymore.
692 if (GetBoolProperty(kIsolatedStorage, false)) {
693 return -1;
694 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700695 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
696
697 DIR* dir;
698 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600699 std::string rootName;
700 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700701 int pidFd;
702 int nsFd;
703 struct stat sb;
704 pid_t child;
705
706 if (!(dir = opendir("/proc"))) {
707 PLOG(ERROR) << "Failed to opendir";
708 return -1;
709 }
710
711 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600712 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
713 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700714 closedir(dir);
715 return -1;
716 }
717
718 // Poke through all running PIDs look for apps running as UID
719 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700720 pid_t pid;
721 if (de->d_type != DT_DIR) continue;
722 if (!android::base::ParseInt(de->d_name, &pid)) continue;
723
Jeff Sharkey66270a22015-06-24 11:49:24 -0700724 pidFd = -1;
725 nsFd = -1;
726
727 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
728 if (pidFd < 0) {
729 goto next;
730 }
731 if (fstat(pidFd, &sb) != 0) {
732 PLOG(WARNING) << "Failed to stat " << de->d_name;
733 goto next;
734 }
735 if (sb.st_uid != uid) {
736 goto next;
737 }
738
739 // Matches so far, but refuse to touch if in root namespace
740 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600741 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700742 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
743 goto next;
744 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600745 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700746 LOG(WARNING) << "Skipping due to root namespace";
747 goto next;
748 }
749
750 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600751 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700752 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700753 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700754 goto next;
755 }
756
757 if (!(child = fork())) {
758 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700759 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700760 _exit(1);
761 }
762
Jeff Sharkey3472e522017-10-06 18:02:53 -0600763 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700764
765 std::string storageSource;
766 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700767 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700768 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700769 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700770 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700771 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700772 } else {
773 // Sane default of no storage visible
774 _exit(0);
775 }
776 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900777 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700778 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
779 << de->d_name;
780 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700781 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900782 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
783 MS_REC | MS_SLAVE, NULL)) == -1) {
784 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
785 << de->d_name;
786 _exit(1);
787 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700788
789 // Mount user-specific symlink helper into place
790 userid_t user_id = multiuser_get_user_id(uid);
791 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
792 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
793 NULL, MS_BIND, NULL)) == -1) {
794 PLOG(ERROR) << "Failed to mount " << userSource << " for "
795 << de->d_name;
796 _exit(1);
797 }
798
Jeff Sharkey66270a22015-06-24 11:49:24 -0700799 _exit(0);
800 }
801
802 if (child == -1) {
803 PLOG(ERROR) << "Failed to fork";
804 goto next;
805 } else {
806 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
807 }
808
809next:
810 close(nsFd);
811 close(pidFd);
812 }
813 closedir(dir);
814 return 0;
815}
816
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700817int VolumeManager::reset() {
818 // Tear down all existing disks/volumes and start from a blank slate so
819 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800820 if (mInternalEmulated != nullptr) {
821 mInternalEmulated->destroy();
822 mInternalEmulated->create();
823 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700824 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700825 disk->destroy();
826 disk->create();
827 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600828 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700829 mAddedUsers.clear();
830 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700831
832 mUserPackages.clear();
833 mAppIds.clear();
834 mSandboxIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700835
836 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
837 unmount_tree("/mnt/user/");
838 // For unmounting dirs under /mnt/storage including the bind mount at /mnt/storage, that's
839 // why no trailing '/'
840 unmount_tree("/mnt/storage");
841 mMntStorageCreated = false;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700842 return 0;
843}
844
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700845// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700846int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700847 if (mInternalEmulated == nullptr) {
848 return 0; // already shutdown
849 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700850 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700851 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700852 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700853 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700854 disk->destroy();
855 }
856 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700857 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700858 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700859 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700860}
861
Jeff Sharkey9c484982015-03-31 10:35:33 -0700862int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700863 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600864 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700865
Jeff Sharkey9c484982015-03-31 10:35:33 -0700866 // First, try gracefully unmounting all known devices
867 if (mInternalEmulated != nullptr) {
868 mInternalEmulated->unmount();
869 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700870 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700871 disk->unmountAll();
872 }
873
874 // Worst case we might have some stale mounts lurking around, so
875 // force unmount those just to be safe.
876 FILE* fp = setmntent("/proc/mounts", "r");
877 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600878 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700879 return -errno;
880 }
881
882 // Some volumes can be stacked on each other, so force unmount in
883 // reverse order to give us the best chance of success.
884 std::list<std::string> toUnmount;
885 mntent* mentry;
886 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600887 auto test = std::string(mentry->mnt_dir);
Tri Vobca5cd72018-04-16 14:27:10 -0700888 if ((android::base::StartsWith(test, "/mnt/") &&
Bowgo Tsaic0cd37b2018-06-29 10:31:07 +0800889 !android::base::StartsWith(test, "/mnt/vendor") &&
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700890 !android::base::StartsWith(test, "/mnt/product") &&
891 !android::base::StartsWith(test, "/mnt/storage")) ||
Tri Vobca5cd72018-04-16 14:27:10 -0700892 android::base::StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600893 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700894 }
895 }
896 endmntent(fp);
897
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700898 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600899 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700900 android::vold::ForceUnmount(path);
901 }
902
903 return 0;
904}
905
Jeff Sharkey3472e522017-10-06 18:02:53 -0600906int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700907 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600908 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700909 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600910 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700911 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600912 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700913 return -EINVAL;
914 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700915}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600916
917static size_t kAppFuseMaxMountPointName = 32;
918
919static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
920 if (name.size() > kAppFuseMaxMountPointName) {
921 LOG(ERROR) << "AppFuse mount name is too long.";
922 return -EINVAL;
923 }
924 for (size_t i = 0; i < name.size(); i++) {
925 if (!isalnum(name[i])) {
926 LOG(ERROR) << "AppFuse mount name contains invalid character.";
927 return -EINVAL;
928 }
929 }
930 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
931 return android::OK;
932}
933
934static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
935 // Remove existing mount.
936 android::vold::ForceUnmount(path);
937
938 const auto opts = android::base::StringPrintf(
939 "fd=%i,"
940 "rootmode=40000,"
941 "default_permissions,"
942 "allow_other,"
943 "user_id=%d,group_id=%d,"
944 "context=\"u:object_r:app_fuse_file:s0\","
945 "fscontext=u:object_r:app_fusefs:s0",
946 device_fd,
947 uid,
948 uid);
949
950 const int result = TEMP_FAILURE_RETRY(mount(
951 "/dev/fuse", path.c_str(), "fuse",
952 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
953 if (result != 0) {
954 PLOG(ERROR) << "Failed to mount " << path;
955 return -errno;
956 }
957
958 return android::OK;
959}
960
961static android::status_t runCommandInNamespace(const std::string& command,
962 uid_t uid,
963 pid_t pid,
964 const std::string& path,
965 int device_fd) {
966 if (DEBUG_APPFUSE) {
967 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
968 << " in namespace " << uid;
969 }
970
971 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
972 if (dir.get() == -1) {
973 PLOG(ERROR) << "Failed to open /proc";
974 return -errno;
975 }
976
977 // Obtains process file descriptor.
978 const std::string pid_str = android::base::StringPrintf("%d", pid);
979 const unique_fd pid_fd(
980 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
981 if (pid_fd.get() == -1) {
982 PLOG(ERROR) << "Failed to open /proc/" << pid;
983 return -errno;
984 }
985
986 // Check UID of process.
987 {
988 struct stat sb;
989 const int result = fstat(pid_fd.get(), &sb);
990 if (result == -1) {
991 PLOG(ERROR) << "Failed to stat /proc/" << pid;
992 return -errno;
993 }
994 if (sb.st_uid != AID_SYSTEM) {
995 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
996 << ", actual=" << sb.st_uid;
997 return -EPERM;
998 }
999 }
1000
1001 // Matches so far, but refuse to touch if in root namespace
1002 {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001003 std::string rootName;
1004 std::string pidName;
1005 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
1006 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
1007 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001008 return -EPERM;
1009 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001010 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001011 LOG(ERROR) << "Don't mount appfuse in root namespace";
1012 return -EPERM;
1013 }
1014 }
1015
1016 // We purposefully leave the namespace open across the fork
1017 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
1018 if (ns_fd.get() < 0) {
1019 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
1020 return -errno;
1021 }
1022
1023 int child = fork();
1024 if (child == 0) {
1025 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
1026 PLOG(ERROR) << "Failed to setns";
1027 _exit(-errno);
1028 }
1029
1030 if (command == "mount") {
1031 _exit(mountInNamespace(uid, device_fd, path));
1032 } else if (command == "unmount") {
1033 // If it's just after all FD opened on mount point are closed, umount2 can fail with
1034 // EBUSY. To avoid the case, specify MNT_DETACH.
1035 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
1036 errno != EINVAL && errno != ENOENT) {
1037 PLOG(ERROR) << "Failed to unmount directory.";
1038 _exit(-errno);
1039 }
1040 if (rmdir(path.c_str()) != 0) {
1041 PLOG(ERROR) << "Failed to remove the mount directory.";
1042 _exit(-errno);
1043 }
1044 _exit(android::OK);
1045 } else {
1046 LOG(ERROR) << "Unknown appfuse command " << command;
1047 _exit(-EPERM);
1048 }
1049 }
1050
1051 if (child == -1) {
1052 PLOG(ERROR) << "Failed to folk child process";
1053 return -errno;
1054 }
1055
1056 android::status_t status;
1057 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
1058
1059 return status;
1060}
1061
1062int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
1063 int32_t ownerGid, std::string* outVolId) {
1064 int id = mNextObbId++;
1065
1066 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1067 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
1068 vol->create();
1069
1070 mObbVolumes.push_back(vol);
1071 *outVolId = vol->getId();
1072 return android::OK;
1073}
1074
1075int VolumeManager::destroyObb(const std::string& volId) {
1076 auto i = mObbVolumes.begin();
1077 while (i != mObbVolumes.end()) {
1078 if ((*i)->getId() == volId) {
1079 (*i)->destroy();
1080 i = mObbVolumes.erase(i);
1081 } else {
1082 ++i;
1083 }
1084 }
1085 return android::OK;
1086}
1087
1088int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
1089 android::base::unique_fd* device_fd) {
1090 std::string name = std::to_string(mountId);
1091
1092 // Check mount point name.
1093 std::string path;
1094 if (getMountPath(uid, name, &path) != android::OK) {
1095 LOG(ERROR) << "Invalid mount point name";
1096 return -1;
1097 }
1098
1099 // Create directories.
1100 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
1101 if (result != android::OK) {
1102 PLOG(ERROR) << "Failed to prepare directory " << path;
1103 return -1;
1104 }
1105
1106 // Open device FD.
1107 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
1108 if (device_fd->get() == -1) {
1109 PLOG(ERROR) << "Failed to open /dev/fuse";
1110 return -1;
1111 }
1112
1113 // Mount.
1114 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
1115}
1116
1117int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
1118 std::string name = std::to_string(mountId);
1119
1120 // Check mount point name.
1121 std::string path;
1122 if (getMountPath(uid, name, &path) != android::OK) {
1123 LOG(ERROR) << "Invalid mount point name";
1124 return -1;
1125 }
1126
1127 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
1128}