blob: 2a8e8b7a5d50f8ed0c7e3c175b433642a817c665 [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;
San Mehatf1b736b2009-10-10 17:22:08 -0700101}
102
103VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800104}
105
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600106int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600107 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600108 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600109 if (access(kPathVirtualDisk, F_OK) != 0) {
110 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
111 }
112
113 if (mVirtualDisk == nullptr) {
114 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
115 LOG(ERROR) << "Failed to create virtual disk";
116 return -1;
117 }
118
119 struct stat buf;
120 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
121 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
122 return -1;
123 }
124
125 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
126 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600127 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700128 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129 }
130 } else {
131 if (mVirtualDisk != nullptr) {
132 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700133 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600134
135 Loop::destroyByDevice(mVirtualDiskPath.c_str());
136 mVirtualDisk = nullptr;
137 }
138
139 if (access(kPathVirtualDisk, F_OK) == 0) {
140 unlink(kPathVirtualDisk);
141 }
142 }
143 return 0;
144}
145
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700146int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800147 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700148 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800149}
150
San Mehatf1b736b2009-10-10 17:22:08 -0700151int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600152 ATRACE_NAME("VolumeManager::start");
153
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700154 // Always start from a clean slate by unmounting everything in
155 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700156 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700157
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600158 Devmapper::destroyAll();
159 Loop::destroyAll();
160
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700161 // Assume that we always have an emulated volume on internal
162 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700163 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700164 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700165 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700166 mInternalEmulated->create();
167
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600168 // Consider creating a virtual disk
169 updateVirtualDisk();
170
San Mehatf1b736b2009-10-10 17:22:08 -0700171 return 0;
172}
173
174int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700175 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700176 mInternalEmulated->destroy();
177 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700178 return 0;
179}
180
San Mehatfd7f5872009-10-12 11:32:47 -0700181void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700182 std::lock_guard<std::mutex> lock(mLock);
183
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700184 if (mDebug) {
185 LOG(VERBOSE) << "----------------";
186 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
187 evt->dump();
188 }
San Mehatf1b736b2009-10-10 17:22:08 -0700189
Mateusz Nowak64403792015-08-03 16:39:19 +0200190 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
191 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192
193 if (devType != "disk") return;
194
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600195 int major = std::stoi(evt->findParam("MAJOR"));
196 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700197 dev_t device = makedev(major, minor);
198
199 switch (evt->getAction()) {
200 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700201 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700202 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800203 // For now, assume that MMC and virtio-blk (the latter is
204 // emulator-specific; see Disk.cpp for details) devices are SD,
205 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700206 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800207 if (major == kMajorBlockMmc
208 || (android::vold::IsRunningInEmulator()
209 && major >= (int) kMajorBlockExperimentalMin
210 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700211 flags |= android::vold::Disk::Flags::kSd;
212 } else {
213 flags |= android::vold::Disk::Flags::kUsb;
214 }
215
216 auto disk = new android::vold::Disk(eventPath, device,
217 source->getNickname(), flags);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700218 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700219 break;
220 }
221 }
222 break;
223 }
224 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700225 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700226 handleDiskChanged(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700227 break;
228 }
229 case NetlinkEvent::Action::kRemove: {
Jeff Sharkey401b2602017-12-14 22:15:20 -0700230 handleDiskRemoved(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700231 break;
232 }
233 default: {
234 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
235 break;
236 }
237 }
238}
239
Jeff Sharkey401b2602017-12-14 22:15:20 -0700240void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
241 // For security reasons, if secure keyguard is showing, wait
242 // until the user unlocks the device to actually touch it
243 if (mSecureKeyguardShowing) {
244 LOG(INFO) << "Found disk at " << disk->getEventPath()
245 << " but delaying scan due to secure keyguard";
246 mPendingDisks.push_back(disk);
247 } else {
248 disk->create();
249 mDisks.push_back(disk);
250 }
251}
252
253void VolumeManager::handleDiskChanged(dev_t device) {
254 for (const auto& disk : mDisks) {
255 if (disk->getDevice() == device) {
256 disk->readMetadata();
257 disk->readPartitions();
258 }
259 }
260
261 // For security reasons, we ignore all pending disks, since
262 // we'll scan them once the device is unlocked
263}
264
265void VolumeManager::handleDiskRemoved(dev_t device) {
266 auto i = mDisks.begin();
267 while (i != mDisks.end()) {
268 if ((*i)->getDevice() == device) {
269 (*i)->destroy();
270 i = mDisks.erase(i);
271 } else {
272 ++i;
273 }
274 }
275 auto j = mPendingDisks.begin();
276 while (j != mPendingDisks.end()) {
277 if ((*j)->getDevice() == device) {
278 j = mPendingDisks.erase(j);
279 } else {
280 ++j;
281 }
282 }
283}
284
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700285void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800286 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700287 mDiskSources.push_back(diskSource);
288}
289
290std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
291 for (auto disk : mDisks) {
292 if (disk->getId() == id) {
293 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700294 }
295 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700296 return nullptr;
297}
San Mehatf1b736b2009-10-10 17:22:08 -0700298
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700299std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800300 // Vold could receive "mount" after "shutdown" command in the extreme case.
301 // If this happens, mInternalEmulated will equal nullptr and
302 // we need to deal with it in order to avoid null pointer crash.
303 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700304 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700305 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700306 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700307 auto vol = disk->findVolume(id);
308 if (vol != nullptr) {
309 return vol;
310 }
311 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600312 for (const auto& vol : mObbVolumes) {
313 if (vol->getId() == id) {
314 return vol;
315 }
316 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700317 return nullptr;
318}
319
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700320void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
321 std::list<std::string>& list) {
322 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700323 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700324 disk->listVolumes(type, list);
325 }
326}
327
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600328int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700329 std::string normalizedGuid;
330 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
331 LOG(WARNING) << "Invalid GUID " << partGuid;
332 return -1;
333 }
334
Paul Crowleyc6433a22017-10-24 14:54:43 -0700335 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700336 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
337 if (unlink(keyPath.c_str()) != 0) {
338 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700339 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700340 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700341 if (e4crypt_is_native()) {
342 if (!e4crypt_destroy_volume_keys(fsUuid)) {
343 success = false;
344 }
345 }
346 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700347}
348
Sudheer Shanka53947a32018-08-01 10:24:13 -0700349int VolumeManager::linkPrimary(userid_t userId, const std::vector<std::string>& packageNames) {
350 if (GetBoolProperty(kIsolatedStorage, false)) {
351 std::string source(StringPrintf("/mnt/runtime/write/%s", mPrimary->getLabel().c_str()));
352 bool isPrimaryEmulated =
353 (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated);
354 if (isPrimaryEmulated) {
355 StringAppendF(&source, "/%d", userId);
356 if (fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
357 PLOG(ERROR) << "fs_prepare_dir failed on " << source;
358 return -errno;
359 }
360 }
361 return mountSandboxesForPrimaryVol(source, userId, packageNames, isPrimaryEmulated);
362 } else {
363 std::string source(mPrimary->getPath());
364 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
365 source = StringPrintf("%s/%d", source.c_str(), userId);
366 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
367 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700368
Sudheer Shanka53947a32018-08-01 10:24:13 -0700369 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
370 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
371 if (errno != ENOENT) {
372 PLOG(WARNING) << "Failed to unlink " << target;
373 }
374 }
375 LOG(DEBUG) << "Linking " << source << " to " << target;
376 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
377 PLOG(WARNING) << "Failed to link";
378 return -errno;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700379 }
380 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700381 return 0;
382}
383
384int VolumeManager::mountSandboxesForPrimaryVol(const std::string& primaryRoot, userid_t userId,
385 const std::vector<std::string>& packageNames, bool isPrimaryEmulated) {
386
387 std::string sandboxRoot = prepareSubDirs(primaryRoot, "Android/sandbox/",
388 0700, AID_ROOT, AID_ROOT);
389 if (sandboxRoot.empty()) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700390 return -errno;
391 }
Sudheer Shankaf768c272018-08-04 10:10:27 -0700392 std::string sharedSandboxRoot;
393 StringAppendF(&sharedSandboxRoot, "%s/shared", sandboxRoot.c_str());
394 // Create shared sandbox base dir for apps with sharedUserIds
395 if (fs_prepare_dir(sharedSandboxRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
396 PLOG(ERROR) << "fs_prepare_dir failed on " << sharedSandboxRoot;
397 return -errno;
398 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700399
400 std::string dataRoot = prepareSubDirs(primaryRoot, "Android/data/",
401 0700, AID_ROOT, AID_ROOT);
402 if (dataRoot.empty()) {
403 return -errno;
404 }
405
406 std::string segment = StringPrintf("%d/package/", userId);
407 std::string mntTargetRoot = prepareSubDirs("/mnt/user", segment.c_str(),
408 0700, AID_ROOT, AID_ROOT);
409 if (mntTargetRoot.empty()) {
410 return -errno;
411 }
412
413 for (auto& packageName : packageNames) {
414 const auto& it = mAppIds.find(packageName);
415 if (it == mAppIds.end()) {
416 PLOG(ERROR) << "appId is not available for " << packageName;
417 continue;
418 }
419 appid_t appId = it->second;
420 std::string sandboxId = mSandboxIds[appId];
421 uid_t uid = multiuser_get_uid(userId, appId);
422
423 // Create [1] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
424 // Create [2] /mnt/user/0/package/<packageName>/emulated/0
425 // Mount [1] at [2]
426 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
427 if (pkgSandboxSourceDir.empty()) {
428 return -errno;
429 }
430 std::string pkgSandboxTargetDir = prepareSandboxTarget(packageName, uid,
431 mPrimary->getLabel(), mntTargetRoot, isPrimaryEmulated);
432 if (pkgSandboxTargetDir.empty()) {
433 return -errno;
434 }
435 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
436 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
437 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
438 << pkgSandboxTargetDir;
439 return -errno;
440 }
441
442 // Create [1] /mnt/runtime/write/emulated/0/Android/data/<packageName>
443 // Create [2] /mnt/user/0/package/<packageName>/emulated/0/Android/data/<packageName>
444 // Mount [1] at [2]
445 std::string pkgDataSourceDir = preparePkgDataSource(packageName, uid, dataRoot);
446 if (pkgDataSourceDir.empty()) {
447 return -errno;
448 }
449 std::string pkgDataTargetDir = preparePkgDataTarget(packageName, uid,
450 pkgSandboxTargetDir);
451 if (pkgDataTargetDir.empty()) {
452 return -errno;
453 }
454 if (TEMP_FAILURE_RETRY(mount(pkgDataSourceDir.c_str(), pkgDataTargetDir.c_str(),
455 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
456 PLOG(ERROR) << "Failed to mount " << pkgDataSourceDir << " at "
457 << pkgDataTargetDir;
458 return -errno;
459 }
460
461 // Create [1] /mnt/user/0/package/<packageName>/self/primary
462 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
463 // Mount [2] at [1]
464 std::string pkgPrimaryTargetDir = prepareSubDirs(
465 StringPrintf("%s/%s", mntTargetRoot.c_str(), packageName.c_str()),
466 "self/primary/", 0755, uid, uid);
467 if (pkgPrimaryTargetDir.empty()) {
468 return -errno;
469 }
470 if (TEMP_FAILURE_RETRY(mount(pkgSandboxTargetDir.c_str(), pkgPrimaryTargetDir.c_str(),
471 nullptr, MS_BIND | MS_REC | MS_SLAVE, nullptr)) == -1) {
472 PLOG(ERROR) << "Failed to mount " << pkgSandboxTargetDir << " at "
473 << pkgPrimaryTargetDir;
474 return -errno;
475 }
476 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700477 return 0;
478}
479
Sudheer Shanka53947a32018-08-01 10:24:13 -0700480std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix,
481 const std::string& subDirs, mode_t mode, uid_t uid, gid_t gid) {
482 std::string path(pathPrefix);
483 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
484 for (size_t i = 0; i < subDirList.size(); ++i) {
485 std::string subDir = subDirList[i];
486 if (subDir.empty()) {
487 continue;
488 }
489 StringAppendF(&path, "/%s", subDir.c_str());
490 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
491 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
492 return kEmptyString;
493 }
494 }
495 return path;
496}
497
498std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
499 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700500 std::string sandboxSourceDir(sandboxRootDir);
501 if (android::base::StartsWith(sandboxId, "shared:")) {
502 StringAppendF(&sandboxSourceDir, "/shared/%s", sandboxId.substr(7).c_str());
503 } else {
504 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
505 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700506 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
507 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
508 return kEmptyString;
509 }
510 return sandboxSourceDir;
511}
512
513std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
514 const std::string& volumeLabel, const std::string& mntTargetRootDir,
515 bool isUserDependent) {
516 std::string segment;
517 if (isUserDependent) {
518 segment = StringPrintf("%s/%s/%d/",
519 packageName.c_str(), volumeLabel.c_str(), multiuser_get_user_id(uid));
520 } else {
521 segment = StringPrintf("%s/%s/",
522 packageName.c_str(), volumeLabel.c_str());
523 }
524 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
525}
526
527std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
528 const std::string& dataRootDir) {
529 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
530 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
531 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
532 return kEmptyString;
533 }
534 return dataSourceDir;
535}
536
537std::string VolumeManager::preparePkgDataTarget(const std::string& packageName, uid_t uid,
538 const std::string& pkgSandboxDir) {
539 std::string segment = StringPrintf("Android/data/%s/", packageName.c_str());
540 return prepareSubDirs(pkgSandboxDir, segment.c_str(), 0755, uid, uid);
541}
542
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700543int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
544 mAddedUsers[userId] = userSerialNumber;
545 return 0;
546}
547
548int VolumeManager::onUserRemoved(userid_t userId) {
549 mAddedUsers.erase(userId);
550 return 0;
551}
552
Sudheer Shankaebaad1c2018-07-31 16:39:59 -0700553int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700554 // Note that sometimes the system will spin up processes from Zygote
555 // before actually starting the user, so we're okay if Zygote
556 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600557 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700558 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
559
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700560 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700561 mUserPackages[userId] = packageNames;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700562 if (mPrimary) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700563 linkPrimary(userId, packageNames);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700564 }
565 return 0;
566}
567
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700568int VolumeManager::onUserStopped(userid_t userId) {
569 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700570 return 0;
571}
572
Sudheer Shankad484aa92018-07-31 10:07:34 -0700573int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
574 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700575 for (size_t i = 0; i < packageNames.size(); ++i) {
576 mAppIds[packageNames[i]] = appIds[i];
577 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700578 return 0;
579}
580
581int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
582 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700583 for (size_t i = 0; i < appIds.size(); ++i) {
584 mSandboxIds[appIds[i]] = sandboxIds[i];
585 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700586 return 0;
587}
588
Jeff Sharkey401b2602017-12-14 22:15:20 -0700589int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
590 mSecureKeyguardShowing = isShowing;
591 if (!mSecureKeyguardShowing) {
592 // Now that secure keyguard has been dismissed, process
593 // any pending disks
594 for (const auto& disk : mPendingDisks) {
595 disk->create();
596 mDisks.push_back(disk);
597 }
598 mPendingDisks.clear();
599 }
600 return 0;
601}
602
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700603int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
604 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700605 for (userid_t userId : mStartedUsers) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700606 linkPrimary(userId, mUserPackages[userId]);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700607 }
608 return 0;
609}
610
Jeff Sharkey3472e522017-10-06 18:02:53 -0600611static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700612 FILE* fp = setmntent("/proc/mounts", "r");
613 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600614 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700615 return -errno;
616 }
617
618 // Some volumes can be stacked on each other, so force unmount in
619 // reverse order to give us the best chance of success.
620 std::list<std::string> toUnmount;
621 mntent* mentry;
622 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600623 auto test = std::string(mentry->mnt_dir) + "/";
Elliott Hughes32a5b9a2017-12-20 12:38:47 -0800624 if (android::base::StartsWith(test, prefix)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600625 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700626 }
627 }
628 endmntent(fp);
629
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700630 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700631 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600632 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700633 }
634 }
635 return 0;
636}
637
Jeff Sharkey66270a22015-06-24 11:49:24 -0700638int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700639 // If the isolated storage is enabled, return -1 since in the isolated storage world, there
640 // are no longer any runtime storage permissions, so this shouldn't be called anymore.
641 if (GetBoolProperty(kIsolatedStorage, false)) {
642 return -1;
643 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700644 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
645
646 DIR* dir;
647 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600648 std::string rootName;
649 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700650 int pidFd;
651 int nsFd;
652 struct stat sb;
653 pid_t child;
654
655 if (!(dir = opendir("/proc"))) {
656 PLOG(ERROR) << "Failed to opendir";
657 return -1;
658 }
659
660 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600661 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
662 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700663 closedir(dir);
664 return -1;
665 }
666
667 // Poke through all running PIDs look for apps running as UID
668 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700669 pid_t pid;
670 if (de->d_type != DT_DIR) continue;
671 if (!android::base::ParseInt(de->d_name, &pid)) continue;
672
Jeff Sharkey66270a22015-06-24 11:49:24 -0700673 pidFd = -1;
674 nsFd = -1;
675
676 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
677 if (pidFd < 0) {
678 goto next;
679 }
680 if (fstat(pidFd, &sb) != 0) {
681 PLOG(WARNING) << "Failed to stat " << de->d_name;
682 goto next;
683 }
684 if (sb.st_uid != uid) {
685 goto next;
686 }
687
688 // Matches so far, but refuse to touch if in root namespace
689 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600690 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700691 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
692 goto next;
693 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600694 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700695 LOG(WARNING) << "Skipping due to root namespace";
696 goto next;
697 }
698
699 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600700 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700701 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700702 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700703 goto next;
704 }
705
706 if (!(child = fork())) {
707 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700708 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700709 _exit(1);
710 }
711
Jeff Sharkey3472e522017-10-06 18:02:53 -0600712 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700713
714 std::string storageSource;
715 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700716 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700717 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700718 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700719 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700720 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700721 } else {
722 // Sane default of no storage visible
723 _exit(0);
724 }
725 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900726 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700727 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
728 << de->d_name;
729 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700730 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900731 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
732 MS_REC | MS_SLAVE, NULL)) == -1) {
733 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
734 << de->d_name;
735 _exit(1);
736 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700737
738 // Mount user-specific symlink helper into place
739 userid_t user_id = multiuser_get_user_id(uid);
740 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
741 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
742 NULL, MS_BIND, NULL)) == -1) {
743 PLOG(ERROR) << "Failed to mount " << userSource << " for "
744 << de->d_name;
745 _exit(1);
746 }
747
Jeff Sharkey66270a22015-06-24 11:49:24 -0700748 _exit(0);
749 }
750
751 if (child == -1) {
752 PLOG(ERROR) << "Failed to fork";
753 goto next;
754 } else {
755 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
756 }
757
758next:
759 close(nsFd);
760 close(pidFd);
761 }
762 closedir(dir);
763 return 0;
764}
765
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700766int VolumeManager::reset() {
767 // Tear down all existing disks/volumes and start from a blank slate so
768 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800769 if (mInternalEmulated != nullptr) {
770 mInternalEmulated->destroy();
771 mInternalEmulated->create();
772 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700773 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700774 disk->destroy();
775 disk->create();
776 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600777 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700778 mAddedUsers.clear();
779 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700780
781 mUserPackages.clear();
782 mAppIds.clear();
783 mSandboxIds.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700784 return 0;
785}
786
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700787// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700788int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700789 if (mInternalEmulated == nullptr) {
790 return 0; // already shutdown
791 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700792 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700793 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700794 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700795 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700796 disk->destroy();
797 }
798 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700799 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700800 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700801 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700802}
803
Jeff Sharkey9c484982015-03-31 10:35:33 -0700804int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700805 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600806 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700807
Jeff Sharkey9c484982015-03-31 10:35:33 -0700808 // First, try gracefully unmounting all known devices
809 if (mInternalEmulated != nullptr) {
810 mInternalEmulated->unmount();
811 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700812 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700813 disk->unmountAll();
814 }
815
816 // Worst case we might have some stale mounts lurking around, so
817 // force unmount those just to be safe.
818 FILE* fp = setmntent("/proc/mounts", "r");
819 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600820 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700821 return -errno;
822 }
823
824 // Some volumes can be stacked on each other, so force unmount in
825 // reverse order to give us the best chance of success.
826 std::list<std::string> toUnmount;
827 mntent* mentry;
828 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600829 auto test = std::string(mentry->mnt_dir);
Tri Vobca5cd72018-04-16 14:27:10 -0700830 if ((android::base::StartsWith(test, "/mnt/") &&
Bowgo Tsaic0cd37b2018-06-29 10:31:07 +0800831 !android::base::StartsWith(test, "/mnt/vendor") &&
832 !android::base::StartsWith(test, "/mnt/product")) ||
Tri Vobca5cd72018-04-16 14:27:10 -0700833 android::base::StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600834 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700835 }
836 }
837 endmntent(fp);
838
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700839 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600840 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700841 android::vold::ForceUnmount(path);
842 }
843
844 return 0;
845}
846
Jeff Sharkey3472e522017-10-06 18:02:53 -0600847int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700848 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600849 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700850 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600851 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700852 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600853 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700854 return -EINVAL;
855 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700856}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600857
858static size_t kAppFuseMaxMountPointName = 32;
859
860static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
861 if (name.size() > kAppFuseMaxMountPointName) {
862 LOG(ERROR) << "AppFuse mount name is too long.";
863 return -EINVAL;
864 }
865 for (size_t i = 0; i < name.size(); i++) {
866 if (!isalnum(name[i])) {
867 LOG(ERROR) << "AppFuse mount name contains invalid character.";
868 return -EINVAL;
869 }
870 }
871 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
872 return android::OK;
873}
874
875static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
876 // Remove existing mount.
877 android::vold::ForceUnmount(path);
878
879 const auto opts = android::base::StringPrintf(
880 "fd=%i,"
881 "rootmode=40000,"
882 "default_permissions,"
883 "allow_other,"
884 "user_id=%d,group_id=%d,"
885 "context=\"u:object_r:app_fuse_file:s0\","
886 "fscontext=u:object_r:app_fusefs:s0",
887 device_fd,
888 uid,
889 uid);
890
891 const int result = TEMP_FAILURE_RETRY(mount(
892 "/dev/fuse", path.c_str(), "fuse",
893 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
894 if (result != 0) {
895 PLOG(ERROR) << "Failed to mount " << path;
896 return -errno;
897 }
898
899 return android::OK;
900}
901
902static android::status_t runCommandInNamespace(const std::string& command,
903 uid_t uid,
904 pid_t pid,
905 const std::string& path,
906 int device_fd) {
907 if (DEBUG_APPFUSE) {
908 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
909 << " in namespace " << uid;
910 }
911
912 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
913 if (dir.get() == -1) {
914 PLOG(ERROR) << "Failed to open /proc";
915 return -errno;
916 }
917
918 // Obtains process file descriptor.
919 const std::string pid_str = android::base::StringPrintf("%d", pid);
920 const unique_fd pid_fd(
921 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
922 if (pid_fd.get() == -1) {
923 PLOG(ERROR) << "Failed to open /proc/" << pid;
924 return -errno;
925 }
926
927 // Check UID of process.
928 {
929 struct stat sb;
930 const int result = fstat(pid_fd.get(), &sb);
931 if (result == -1) {
932 PLOG(ERROR) << "Failed to stat /proc/" << pid;
933 return -errno;
934 }
935 if (sb.st_uid != AID_SYSTEM) {
936 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
937 << ", actual=" << sb.st_uid;
938 return -EPERM;
939 }
940 }
941
942 // Matches so far, but refuse to touch if in root namespace
943 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600944 std::string rootName;
945 std::string pidName;
946 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
947 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
948 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600949 return -EPERM;
950 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600951 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600952 LOG(ERROR) << "Don't mount appfuse in root namespace";
953 return -EPERM;
954 }
955 }
956
957 // We purposefully leave the namespace open across the fork
958 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
959 if (ns_fd.get() < 0) {
960 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
961 return -errno;
962 }
963
964 int child = fork();
965 if (child == 0) {
966 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
967 PLOG(ERROR) << "Failed to setns";
968 _exit(-errno);
969 }
970
971 if (command == "mount") {
972 _exit(mountInNamespace(uid, device_fd, path));
973 } else if (command == "unmount") {
974 // If it's just after all FD opened on mount point are closed, umount2 can fail with
975 // EBUSY. To avoid the case, specify MNT_DETACH.
976 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
977 errno != EINVAL && errno != ENOENT) {
978 PLOG(ERROR) << "Failed to unmount directory.";
979 _exit(-errno);
980 }
981 if (rmdir(path.c_str()) != 0) {
982 PLOG(ERROR) << "Failed to remove the mount directory.";
983 _exit(-errno);
984 }
985 _exit(android::OK);
986 } else {
987 LOG(ERROR) << "Unknown appfuse command " << command;
988 _exit(-EPERM);
989 }
990 }
991
992 if (child == -1) {
993 PLOG(ERROR) << "Failed to folk child process";
994 return -errno;
995 }
996
997 android::status_t status;
998 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
999
1000 return status;
1001}
1002
1003int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
1004 int32_t ownerGid, std::string* outVolId) {
1005 int id = mNextObbId++;
1006
1007 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1008 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
1009 vol->create();
1010
1011 mObbVolumes.push_back(vol);
1012 *outVolId = vol->getId();
1013 return android::OK;
1014}
1015
1016int VolumeManager::destroyObb(const std::string& volId) {
1017 auto i = mObbVolumes.begin();
1018 while (i != mObbVolumes.end()) {
1019 if ((*i)->getId() == volId) {
1020 (*i)->destroy();
1021 i = mObbVolumes.erase(i);
1022 } else {
1023 ++i;
1024 }
1025 }
1026 return android::OK;
1027}
1028
1029int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
1030 android::base::unique_fd* device_fd) {
1031 std::string name = std::to_string(mountId);
1032
1033 // Check mount point name.
1034 std::string path;
1035 if (getMountPath(uid, name, &path) != android::OK) {
1036 LOG(ERROR) << "Invalid mount point name";
1037 return -1;
1038 }
1039
1040 // Create directories.
1041 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
1042 if (result != android::OK) {
1043 PLOG(ERROR) << "Failed to prepare directory " << path;
1044 return -1;
1045 }
1046
1047 // Open device FD.
1048 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
1049 if (device_fd->get() == -1) {
1050 PLOG(ERROR) << "Failed to open /dev/fuse";
1051 return -1;
1052 }
1053
1054 // Mount.
1055 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
1056}
1057
1058int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
1059 std::string name = std::to_string(mountId);
1060
1061 // Check mount point name.
1062 std::string path;
1063 if (getMountPath(uid, name, &path) != android::OK) {
1064 LOG(ERROR) << "Invalid mount point name";
1065 return -1;
1066 }
1067
1068 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
1069}