blob: 91ee41326a8cfc353aabad139f2fc66863e1f8d2 [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080022#include <mntent.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080028#include <sys/stat.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070029#include <sys/sysmacros.h>
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070030#include <sys/types.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070033#include <array>
San Mehata19b2502010-01-06 10:33:53 -080034
San Mehata2677e42009-12-13 10:40:18 -080035#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070036
Elliott Hughes7e128fb2015-12-04 15:50:53 -080037#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070038#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060039#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080040#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070041#include <android-base/strings.h>
42
Jeff Sharkey71ebe152013-09-17 17:24:38 -070043#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060044#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070045
Robert Craigb9e3ba52014-02-04 10:53:00 -050046#include <selinux/android.h>
47
San Mehatfd7f5872009-10-12 11:32:47 -070048#include <sysutils/NetlinkEvent.h>
49
Kenny Root344ca102012-04-03 17:23:01 -070050#include <private/android_filesystem_config.h>
51
Eric Biggersa701c452018-10-23 13:06:55 -070052#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070053
54#include "Devmapper.h"
Eric Biggersa701c452018-10-23 13:06:55 -070055#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080056#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070057#include "NetlinkManager.h"
58#include "Process.h"
59#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070060#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070061#include "VoldUtil.h"
62#include "VolumeManager.h"
63#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070064#include "fs/Ext4.h"
65#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070066#include "model/EmulatedVolume.h"
67#include "model/ObbVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090068#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080069
Sudheer Shanka53947a32018-08-01 10:24:13 -070070using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070071using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070072using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070073using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060074using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070075
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060076static const char* kPathUserMount = "/mnt/user";
77static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
78
Sudheer Shanka53947a32018-08-01 10:24:13 -070079static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060080static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
81
Sudheer Shanka53947a32018-08-01 10:24:13 -070082static const std::string kEmptyString("");
83
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060084/* 512MiB is large enough for testing purposes */
85static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070086
Jeff Sharkey36801cc2015-03-13 16:09:20 -070087static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080088static const unsigned int kMajorBlockExperimentalMin = 240;
89static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070090
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070091VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070092
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070093VolumeManager* VolumeManager::Instance() {
94 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070095 return sInstance;
96}
97
98VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080099 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600100 mNextObbId = 0;
Risan8c9f3322018-10-29 08:52:56 +0900101 mNextStubVolumeId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700102 // For security reasons, assume that a secure keyguard is
103 // showing until we hear otherwise
104 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700105}
106
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700107VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800108
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600109int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600110 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700111 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600112 if (access(kPathVirtualDisk, F_OK) != 0) {
113 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
114 }
115
116 if (mVirtualDisk == nullptr) {
117 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
118 LOG(ERROR) << "Failed to create virtual disk";
119 return -1;
120 }
121
122 struct stat buf;
123 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
124 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
125 return -1;
126 }
127
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700128 auto disk = new android::vold::Disk(
129 "virtual", buf.st_rdev, "virtual",
130 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600131 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700132 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600133 }
134 } else {
135 if (mVirtualDisk != nullptr) {
136 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700137 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600138
139 Loop::destroyByDevice(mVirtualDiskPath.c_str());
140 mVirtualDisk = nullptr;
141 }
142
143 if (access(kPathVirtualDisk, F_OK) == 0) {
144 unlink(kPathVirtualDisk);
145 }
146 }
147 return 0;
148}
149
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700150int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800151 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700152 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800153}
154
San Mehatf1b736b2009-10-10 17:22:08 -0700155int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600156 ATRACE_NAME("VolumeManager::start");
157
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700158 // Always start from a clean slate by unmounting everything in
159 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700160 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700161
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600162 Devmapper::destroyAll();
163 Loop::destroyAll();
164
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700165 // Assume that we always have an emulated volume on internal
166 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700167 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700168 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700169 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700170 mInternalEmulated->create();
171
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600172 // Consider creating a virtual disk
173 updateVirtualDisk();
174
San Mehatf1b736b2009-10-10 17:22:08 -0700175 return 0;
176}
177
178int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700179 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700180 mInternalEmulated->destroy();
181 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700182 return 0;
183}
184
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700185void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700186 std::lock_guard<std::mutex> lock(mLock);
187
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700188 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700189 LOG(DEBUG) << "----------------";
190 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700191 evt->dump();
192 }
San Mehatf1b736b2009-10-10 17:22:08 -0700193
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700194 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
195 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700196
197 if (devType != "disk") return;
198
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600199 int major = std::stoi(evt->findParam("MAJOR"));
200 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700201 dev_t device = makedev(major, minor);
202
203 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700204 case NetlinkEvent::Action::kAdd: {
205 for (const auto& source : mDiskSources) {
206 if (source->matches(eventPath)) {
207 // For now, assume that MMC and virtio-blk (the latter is
208 // emulator-specific; see Disk.cpp for details) devices are SD,
209 // and that everything else is USB
210 int flags = source->getFlags();
211 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
212 major >= (int)kMajorBlockExperimentalMin &&
213 major <= (int)kMajorBlockExperimentalMax)) {
214 flags |= android::vold::Disk::Flags::kSd;
215 } else {
216 flags |= android::vold::Disk::Flags::kUsb;
217 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700218
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700219 auto disk =
220 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
221 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
222 break;
223 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700224 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700225 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700226 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700227 case NetlinkEvent::Action::kChange: {
228 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
229 handleDiskChanged(device);
230 break;
231 }
232 case NetlinkEvent::Action::kRemove: {
233 handleDiskRemoved(device);
234 break;
235 }
236 default: {
237 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
238 break;
239 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700240 }
241}
242
Jeff Sharkey401b2602017-12-14 22:15:20 -0700243void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
244 // For security reasons, if secure keyguard is showing, wait
245 // until the user unlocks the device to actually touch it
246 if (mSecureKeyguardShowing) {
247 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700248 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700249 mPendingDisks.push_back(disk);
250 } else {
251 disk->create();
252 mDisks.push_back(disk);
253 }
254}
255
256void VolumeManager::handleDiskChanged(dev_t device) {
257 for (const auto& disk : mDisks) {
258 if (disk->getDevice() == device) {
259 disk->readMetadata();
260 disk->readPartitions();
261 }
262 }
263
264 // For security reasons, we ignore all pending disks, since
265 // we'll scan them once the device is unlocked
266}
267
268void VolumeManager::handleDiskRemoved(dev_t device) {
269 auto i = mDisks.begin();
270 while (i != mDisks.end()) {
271 if ((*i)->getDevice() == device) {
272 (*i)->destroy();
273 i = mDisks.erase(i);
274 } else {
275 ++i;
276 }
277 }
278 auto j = mPendingDisks.begin();
279 while (j != mPendingDisks.end()) {
280 if ((*j)->getDevice() == device) {
281 j = mPendingDisks.erase(j);
282 } else {
283 ++j;
284 }
285 }
286}
287
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700288void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800289 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700290 mDiskSources.push_back(diskSource);
291}
292
293std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
294 for (auto disk : mDisks) {
295 if (disk->getId() == id) {
296 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700297 }
298 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700299 return nullptr;
300}
San Mehatf1b736b2009-10-10 17:22:08 -0700301
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700302std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800303 // Vold could receive "mount" after "shutdown" command in the extreme case.
304 // If this happens, mInternalEmulated will equal nullptr and
305 // we need to deal with it in order to avoid null pointer crash.
306 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700307 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700308 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700309 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700310 auto vol = disk->findVolume(id);
311 if (vol != nullptr) {
312 return vol;
313 }
314 }
Risan8c9f3322018-10-29 08:52:56 +0900315 for (const auto& vol : mStubVolumes) {
316 if (vol->getId() == id) {
317 return vol;
318 }
319 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600320 for (const auto& vol : mObbVolumes) {
321 if (vol->getId() == id) {
322 return vol;
323 }
324 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700325 return nullptr;
326}
327
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700328void VolumeManager::listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700329 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700330 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700331 disk->listVolumes(type, list);
332 }
333}
334
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600335int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700336 std::string normalizedGuid;
337 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
338 LOG(WARNING) << "Invalid GUID " << partGuid;
339 return -1;
340 }
341
Paul Crowleyc6433a22017-10-24 14:54:43 -0700342 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700343 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
344 if (unlink(keyPath.c_str()) != 0) {
345 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700346 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700347 }
Eric Biggersa701c452018-10-23 13:06:55 -0700348 if (fscrypt_is_native()) {
349 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700350 success = false;
351 }
352 }
353 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700354}
355
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700356int VolumeManager::linkPrimary(userid_t userId) {
357 std::string source(mPrimary->getPath());
358 if (mPrimary->isEmulated()) {
359 source = StringPrintf("%s/%d", source.c_str(), userId);
360 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
361 }
362
363 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
364 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
365 if (errno != ENOENT) {
366 PLOG(WARNING) << "Failed to unlink " << target;
367 }
368 }
369 LOG(DEBUG) << "Linking " << source << " to " << target;
370 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
371 PLOG(WARNING) << "Failed to link";
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700372 return -errno;
373 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700374 return 0;
375}
376
377int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
378 const std::string& mntTargetRoot,
379 const std::string& packageName, const char* dirName) {
380 std::string mntSourceDir =
381 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
382 std::string mntTargetDir =
383 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
384 if (umount2(mntTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL && errno != ENOENT) {
385 PLOG(ERROR) << "Failed to unmount " << mntTargetDir;
386 return -1;
387 }
388 if (TEMP_FAILURE_RETRY(mount(mntSourceDir.c_str(), mntTargetDir.c_str(), nullptr,
389 MS_BIND | MS_REC, nullptr)) == -1) {
390 PLOG(ERROR) << "Failed to mount " << mntSourceDir << " to " << mntTargetDir;
391 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700392 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700393 if (TEMP_FAILURE_RETRY(
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700394 mount(nullptr, mntTargetDir.c_str(), nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
395 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTargetDir;
396 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700397 }
398 return 0;
399}
400
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700401int VolumeManager::mountPkgSpecificDirsForRunningProcs(
402 userid_t userId, const std::vector<std::string>& packageNames,
403 const std::vector<std::string>& visibleVolLabels) {
404 // TODO: New processes could be started while traversing over the existing
405 // processes which would end up not having the necessary bind mounts. This
406 // issue needs to be fixed, may be by doing multiple passes here?
407 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
408 if (!dirp) {
409 PLOG(ERROR) << "Failed to opendir /proc";
410 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700411 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700412
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700413 std::string rootName;
414 // Figure out root namespace to compare against below
415 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
416 PLOG(ERROR) << "Failed to read root namespace";
417 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700418 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700419
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700420 struct stat fullWriteSb;
421 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &fullWriteSb)) == -1) {
422 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
423 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700424 }
425
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700426 std::unordered_set<appid_t> validAppIds;
427 for (auto& package : packageNames) {
428 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700429 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700430 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700431
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700432 struct dirent* de;
433 // Poke through all running PIDs look for apps running in userId
434 while ((de = readdir(dirp.get()))) {
435 pid_t pid;
436 if (de->d_type != DT_DIR) continue;
437 if (!android::base::ParseInt(de->d_name, &pid)) continue;
438
439 const unique_fd pidFd(
440 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
441 if (pidFd.get() < 0) {
442 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700443 continue;
444 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700445 struct stat sb;
446 if (fstat(pidFd.get(), &sb) != 0) {
447 PLOG(WARNING) << "Failed to stat " << de->d_name;
448 continue;
449 }
450 if (multiuser_get_user_id(sb.st_uid) != userId) {
451 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700452 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700453
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700454 // Matches so far, but refuse to touch if in root namespace
455 LOG(VERBOSE) << "Found matching PID " << de->d_name;
456 std::string pidName;
457 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
458 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
459 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700460 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700461 if (rootName == pidName) {
462 LOG(WARNING) << "Skipping due to root namespace";
463 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700464 }
465
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700466 // Only update the mount points of processes running with one of validAppIds.
467 // This should skip any isolated uids.
468 appid_t appId = multiuser_get_app_id(sb.st_uid);
469 if (validAppIds.find(appId) == validAppIds.end()) {
470 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700471 }
472
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700473 std::vector<std::string> packagesForUid;
474 for (auto& package : userPackages) {
475 if (mAppIds[package] == appId) {
476 packagesForUid.push_back(package);
477 }
478 }
479 if (packagesForUid.empty()) {
480 continue;
481 }
482 const std::string& sandboxId = mSandboxIds[appId];
483
484 // We purposefully leave the namespace open across the fork
485 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
486 if (nsFd.get() < 0) {
487 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
488 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700489 }
490
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700491 pid_t child;
492 if (!(child = fork())) {
493 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
494 PLOG(ERROR) << "Failed to setns for " << de->d_name;
495 _exit(1);
496 }
497
498 struct stat storageSb;
499 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
500 PLOG(ERROR) << "Failed to stat /storage";
501 _exit(1);
502 }
503
504 // Some packages have access to full external storage, identify processes belonging
505 // to those packages by comparing inode no.s of /mnt/runtime/write and /storage
506 if (storageSb.st_dev == fullWriteSb.st_dev && storageSb.st_ino == fullWriteSb.st_ino) {
507 _exit(0);
508 } else {
509 // Some packages don't have access to external storage and processes belonging to
510 // those packages don't have anything mounted at /storage. So, identify those
511 // processes by comparing inode no.s of /mnt/user/%d/package/%s
512 // and /storage
513 std::string pkgStorageSource;
514 for (auto& package : packagesForUid) {
515 std::string sandbox =
516 StringPrintf("/mnt/user/%d/package/%s", userId, package.c_str());
517 struct stat s;
518 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &s)) == -1) {
519 PLOG(ERROR) << "Failed to stat " << sandbox;
520 _exit(1);
521 }
522 if (storageSb.st_dev == s.st_dev && storageSb.st_ino == s.st_ino) {
523 pkgStorageSource = sandbox;
524 break;
525 }
526 }
527 if (pkgStorageSource.empty()) {
528 _exit(0);
529 }
530 }
531
532 for (auto& volumeLabel : visibleVolLabels) {
533 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
534 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
535 if (volumeLabel == "emulated") {
536 StringAppendF(&mntSource, "/%d", userId);
537 StringAppendF(&mntTarget, "/%d", userId);
538 }
539 for (auto& package : packagesForUid) {
540 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
541 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
542 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
543 }
544 }
545 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700546 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700547
548 if (child == -1) {
549 PLOG(ERROR) << "Failed to fork";
550 } else {
551 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700552 }
553 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700554 return 0;
555}
556
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700557int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
558 const std::vector<std::string>& visibleVolLabels) {
559 if (visibleVolLabels.empty()) {
560 return 0;
561 }
562 for (auto& volumeLabel : visibleVolLabels) {
563 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
564 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
565 if (isVolPrimaryEmulated) {
566 StringAppendF(&volumeRoot, "/%d", userId);
567 if (fs_prepare_dir(volumeRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
568 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeRoot;
569 return -errno;
570 }
571 }
572
573 std::string sandboxRoot =
574 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
575 if (sandboxRoot.empty()) {
576 return -errno;
577 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700578
579 if (!createPkgSpecificDirRoots(volumeRoot)) {
580 return -errno;
581 }
582
583 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
584 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
585 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
586 return -errno;
587 }
588 mntTargetRoot.append("/package");
589 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
590 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
591 return -errno;
592 }
593
594 for (auto& packageName : packageNames) {
595 const auto& it = mAppIds.find(packageName);
596 if (it == mAppIds.end()) {
597 PLOG(ERROR) << "appId is not available for " << packageName;
598 continue;
599 }
600 appid_t appId = it->second;
601 std::string sandboxId = mSandboxIds[appId];
602 uid_t uid = multiuser_get_uid(userId, appId);
603
604 // [1] Create /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
605 // [2] Create /mnt/user/0/package/<packageName>/emulated/0
606 // Mount [1] at [2]
607 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
608 if (pkgSandboxSourceDir.empty()) {
609 return -errno;
610 }
611 std::string pkgSandboxTargetDir = prepareSandboxTarget(
612 packageName, uid, volumeLabel, mntTargetRoot, isVolPrimaryEmulated);
613 if (pkgSandboxTargetDir.empty()) {
614 return -errno;
615 }
616 if (umount2(pkgSandboxTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
617 errno != ENOENT) {
618 PLOG(ERROR) << "Failed to unmount " << pkgSandboxTargetDir;
619 return -errno;
620 }
621 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
622 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
623 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
624 << pkgSandboxTargetDir;
625 return -errno;
626 }
627 if (TEMP_FAILURE_RETRY(mount(nullptr, pkgSandboxTargetDir.c_str(), nullptr,
628 MS_SLAVE | MS_REC, nullptr)) == -1) {
629 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
630 << pkgSandboxTargetDir;
631 return -errno;
632 }
633
634 // Create Android/{data,media,obb}/<packageName> segments at
635 // [1] /mnt/runtime/write/emulated/0/ and
636 // [2] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>/emulated/0/
637 if (!createPkgSpecificDirs(packageName, uid, volumeRoot, pkgSandboxSourceDir)) {
638 return -errno;
639 }
640
641 if (volumeLabel == mPrimary->getLabel()) {
642 // Create [1] /mnt/user/0/package/<packageName>/self/
643 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
644 // Mount [2] at [1]
645 std::string pkgPrimaryTargetDir =
646 StringPrintf("%s/%s/self", mntTargetRoot.c_str(), packageName.c_str());
647 if (fs_prepare_dir(pkgPrimaryTargetDir.c_str(), 0755, uid, uid) != 0) {
648 PLOG(ERROR) << "Failed to fs_prepare_dir on " << pkgPrimaryTargetDir;
649 return -errno;
650 }
651 StringAppendF(&pkgPrimaryTargetDir, "/primary");
652 std::string primarySource(mPrimary->getPath());
653 if (isVolPrimaryEmulated) {
654 StringAppendF(&primarySource, "/%d", userId);
655 }
656 if (TEMP_FAILURE_RETRY(unlink(pkgPrimaryTargetDir.c_str()))) {
657 if (errno != ENOENT) {
658 PLOG(ERROR) << "Failed to unlink " << pkgPrimaryTargetDir;
659 }
660 }
661 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), pkgPrimaryTargetDir.c_str()))) {
662 PLOG(ERROR) << "Failed to link " << primarySource << " at "
663 << pkgPrimaryTargetDir;
664 return -errno;
665 }
666 }
667 }
668 }
669 mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels);
670 return 0;
671}
672
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700673std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
674 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700675 std::string path(pathPrefix);
676 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
677 for (size_t i = 0; i < subDirList.size(); ++i) {
678 std::string subDir = subDirList[i];
679 if (subDir.empty()) {
680 continue;
681 }
682 StringAppendF(&path, "/%s", subDir.c_str());
683 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
684 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
685 return kEmptyString;
686 }
687 }
688 return path;
689}
690
691std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700692 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700693 std::string sandboxSourceDir(sandboxRootDir);
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700694 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700695 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
696 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
697 return kEmptyString;
698 }
699 return sandboxSourceDir;
700}
701
702std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700703 const std::string& volumeLabel,
704 const std::string& mntTargetRootDir,
705 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700706 std::string segment;
707 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700708 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
709 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700710 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700711 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700712 }
713 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
714}
715
716std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700717 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700718 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
719 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
720 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
721 return kEmptyString;
722 }
723 return dataSourceDir;
724}
725
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700726bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
727 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
728 if (fs_prepare_dir(volumeAndroidRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
729 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeAndroidRoot;
730 return false;
731 }
732 std::array<std::string, 3> dirs = {"data", "media", "obb"};
733 for (auto& dir : dirs) {
734 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
735 if (fs_prepare_dir(path.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
736 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
737 return false;
738 }
739 }
740 return true;
741}
742
743bool VolumeManager::createPkgSpecificDirs(const std::string& packageName, uid_t uid,
744 const std::string& volumeRoot,
745 const std::string& sandboxDirRoot) {
746 std::array<std::string, 3> dirs = {"data", "media", "obb"};
747 for (auto& dir : dirs) {
748 std::string sourceDir = StringPrintf("%s/Android/%s", volumeRoot.c_str(), dir.c_str());
749 if (prepareSubDirs(sourceDir, packageName, 0755, uid, uid).empty()) {
750 return false;
751 }
752 std::string sandboxSegment =
753 StringPrintf("Android/%s/%s/", dir.c_str(), packageName.c_str());
754 if (prepareSubDirs(sandboxDirRoot, sandboxSegment, 0755, uid, uid).empty()) {
755 return false;
756 }
757 }
758 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700759}
760
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700761int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
762 mAddedUsers[userId] = userSerialNumber;
763 return 0;
764}
765
766int VolumeManager::onUserRemoved(userid_t userId) {
767 mAddedUsers.erase(userId);
768 return 0;
769}
770
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700771int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
772 const std::vector<int>& appIds,
773 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700774 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700775 // Note that sometimes the system will spin up processes from Zygote
776 // before actually starting the user, so we're okay if Zygote
777 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600778 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700779 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
780
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700781 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700782 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700783 for (size_t i = 0; i < packageNames.size(); ++i) {
784 mAppIds[packageNames[i]] = appIds[i];
785 mSandboxIds[appIds[i]] = sandboxIds[i];
786 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700787 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700788 linkPrimary(userId);
789 }
790 if (GetBoolProperty(kIsolatedStorage, false)) {
791 std::vector<std::string> visibleVolLabels;
792 for (auto& volId : mVisibleVolumeIds) {
793 auto vol = findVolume(volId);
794 userid_t mountUserId = vol->getMountUserId();
795 if (mountUserId == userId || vol->isEmulated()) {
796 visibleVolLabels.push_back(vol->getLabel());
797 }
798 }
799 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
800 return -errno;
801 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700802 }
803 return 0;
804}
805
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700806int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700807 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700808 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700809
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700810 if (GetBoolProperty(kIsolatedStorage, false)) {
811 mUserPackages.erase(userId);
812 std::string mntTargetDir = StringPrintf("/mnt/user/%d", userId);
813 if (android::vold::UnmountTree(mntTargetDir) != 0) {
814 PLOG(ERROR) << "unmountTree on " << mntTargetDir << " failed";
815 return -errno;
816 }
817 if (android::vold::DeleteDirContentsAndDir(mntTargetDir) < 0) {
818 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << mntTargetDir;
819 return -errno;
820 }
821 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << mntTargetDir;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700822 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700823 return 0;
824}
825
Sudheer Shankad484aa92018-07-31 10:07:34 -0700826int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700827 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700828 for (size_t i = 0; i < packageNames.size(); ++i) {
829 mAppIds[packageNames[i]] = appIds[i];
830 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700831 return 0;
832}
833
834int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700835 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700836 for (size_t i = 0; i < appIds.size(); ++i) {
837 mSandboxIds[appIds[i]] = sandboxIds[i];
838 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700839 return 0;
840}
841
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700842int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
843 const std::string& sandboxId, userid_t userId) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700844 if (!GetBoolProperty(kIsolatedStorage, false)) {
845 return 0;
846 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
847 // User not started, no need to do anything now. Required bind mounts for the package will
848 // be created when the user starts.
849 return 0;
850 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700851 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700852 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700853 mUserPackages[userId].push_back(packageName);
854 mAppIds[packageName] = appId;
855 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700856
857 std::vector<std::string> visibleVolLabels;
858 for (auto& volId : mVisibleVolumeIds) {
859 auto vol = findVolume(volId);
860 userid_t mountUserId = vol->getMountUserId();
861 if (mountUserId == userId || vol->isEmulated()) {
862 visibleVolLabels.push_back(vol->getLabel());
863 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700864 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700865 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700866}
867
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700868int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700869 const std::string& sandboxId, userid_t userId) {
870 if (!GetBoolProperty(kIsolatedStorage, false)) {
871 return 0;
872 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700873 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
874 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700875 auto& userPackages = mUserPackages[userId];
876 std::remove(userPackages.begin(), userPackages.end(), packageName);
877 // If the package is not uninstalled in any other users, remove appId and sandboxId
878 // corresponding to it from the internal state.
879 bool installedInAnyUser = false;
880 for (auto& it : mUserPackages) {
881 auto& packages = it.second;
882 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
883 installedInAnyUser = true;
884 break;
885 }
886 }
887 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700888 const auto& entry = mAppIds.find(packageName);
889 if (entry != mAppIds.end()) {
890 mSandboxIds.erase(entry->second);
891 mAppIds.erase(entry);
892 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700893 }
894
895 std::vector<std::string> visibleVolLabels;
896 for (auto& volId : mVisibleVolumeIds) {
897 auto vol = findVolume(volId);
898 userid_t mountUserId = vol->getMountUserId();
899 if (mountUserId == userId || vol->isEmulated()) {
900 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
901 return -errno;
902 }
903 }
904 }
905 return 0;
906}
907
908int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
909 const std::string& sandboxId, userid_t userId,
910 const std::string& volLabel) {
911 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
912 << ", volLabel=" << volLabel;
913 std::string pkgSandboxTarget =
914 StringPrintf("/mnt/user/%d/package/%s", userId, packageName.c_str());
915 if (android::vold::UnmountTree(pkgSandboxTarget)) {
916 PLOG(ERROR) << "UnmountTree failed on " << pkgSandboxTarget;
917 }
918
919 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
920 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
921 StringAppendF(&sandboxDir, "/%d", userId);
922 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700923 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700924
925 if (android::vold::DeleteDirContentsAndDir(sandboxDir) < 0) {
926 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
927 return -errno;
928 }
929 return 0;
930}
931
Jeff Sharkey401b2602017-12-14 22:15:20 -0700932int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
933 mSecureKeyguardShowing = isShowing;
934 if (!mSecureKeyguardShowing) {
935 // Now that secure keyguard has been dismissed, process
936 // any pending disks
937 for (const auto& disk : mPendingDisks) {
938 disk->create();
939 mDisks.push_back(disk);
940 }
941 mPendingDisks.clear();
942 }
943 return 0;
944}
945
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700946int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
947 if (!GetBoolProperty(kIsolatedStorage, false)) {
948 return 0;
949 }
950
951 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
952 return 0;
953 }
954
955 mVisibleVolumeIds.insert(vol->getId());
956 userid_t mountUserId = vol->getMountUserId();
957 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
958 // We don't want to create another shared_ptr here because then we will end up with
959 // two shared_ptrs owning the underlying pointer without sharing it.
960 mPrimary = findVolume(vol->getId());
961 for (userid_t userId : mStartedUsers) {
962 if (linkPrimary(userId) != 0) {
963 return -errno;
964 }
965 }
966 }
967 if (vol->isEmulated()) {
968 for (userid_t userId : mStartedUsers) {
969 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
970 return -errno;
971 }
972 }
973 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
974 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
975 return -errno;
976 }
977 }
978 return 0;
979}
980
981int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
982 if (!GetBoolProperty(kIsolatedStorage, false)) {
983 return 0;
984 }
985
986 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
987 return 0;
988 }
989
990 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
991 mPrimary = nullptr;
992 }
993
994 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
995 userid_t mountUserId = vol->getMountUserId();
996 if (vol->isEmulated()) {
997 for (userid_t userId : mStartedUsers) {
998 if (destroySandboxesForVol(vol, userId) != 0) {
999 return -errno;
1000 }
1001 }
1002 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1003 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1004 return -errno;
1005 }
1006 }
1007 return 0;
1008}
1009
1010int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1011 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
1012 const std::vector<std::string>& packageNames = mUserPackages[userId];
1013 for (auto& packageName : packageNames) {
1014 std::string volSandboxRoot = StringPrintf("/mnt/user/%d/package/%s/%s", userId,
1015 packageName.c_str(), vol->getLabel().c_str());
1016 if (android::vold::UnmountTree(volSandboxRoot) != 0) {
1017 PLOG(ERROR) << "unmountTree on " << volSandboxRoot << " failed";
1018 continue;
1019 }
1020 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1021 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1022 continue;
1023 }
1024 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
1025 }
1026 return 0;
1027}
1028
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001029int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001030 if (GetBoolProperty(kIsolatedStorage, false)) {
1031 return 0;
1032 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001033 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001034 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001035 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001036 }
1037 return 0;
1038}
1039
Jeff Sharkey66270a22015-06-24 11:49:24 -07001040int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
Sudheer Shanka53947a32018-08-01 10:24:13 -07001041 // If the isolated storage is enabled, return -1 since in the isolated storage world, there
1042 // are no longer any runtime storage permissions, so this shouldn't be called anymore.
1043 if (GetBoolProperty(kIsolatedStorage, false)) {
1044 return -1;
1045 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001046 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1047
1048 DIR* dir;
1049 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001050 std::string rootName;
1051 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001052 int pidFd;
1053 int nsFd;
1054 struct stat sb;
1055 pid_t child;
1056
1057 if (!(dir = opendir("/proc"))) {
1058 PLOG(ERROR) << "Failed to opendir";
1059 return -1;
1060 }
1061
1062 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001063 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1064 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001065 closedir(dir);
1066 return -1;
1067 }
1068
1069 // Poke through all running PIDs look for apps running as UID
1070 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001071 pid_t pid;
1072 if (de->d_type != DT_DIR) continue;
1073 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1074
Jeff Sharkey66270a22015-06-24 11:49:24 -07001075 pidFd = -1;
1076 nsFd = -1;
1077
1078 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1079 if (pidFd < 0) {
1080 goto next;
1081 }
1082 if (fstat(pidFd, &sb) != 0) {
1083 PLOG(WARNING) << "Failed to stat " << de->d_name;
1084 goto next;
1085 }
1086 if (sb.st_uid != uid) {
1087 goto next;
1088 }
1089
1090 // Matches so far, but refuse to touch if in root namespace
1091 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001092 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001093 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1094 goto next;
1095 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001096 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001097 LOG(WARNING) << "Skipping due to root namespace";
1098 goto next;
1099 }
1100
1101 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001102 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -07001103 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001104 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001105 goto next;
1106 }
1107
1108 if (!(child = fork())) {
1109 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001110 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001111 _exit(1);
1112 }
1113
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001114 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001115
1116 std::string storageSource;
1117 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001118 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001119 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001120 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001121 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001122 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001123 } else {
1124 // Sane default of no storage visible
1125 _exit(0);
1126 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001127 if (TEMP_FAILURE_RETRY(
1128 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1129 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001130 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001131 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001132 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1133 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001134 _exit(1);
1135 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001136
1137 // Mount user-specific symlink helper into place
1138 userid_t user_id = multiuser_get_user_id(uid);
1139 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001140 if (TEMP_FAILURE_RETRY(
1141 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1142 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001143 _exit(1);
1144 }
1145
Jeff Sharkey66270a22015-06-24 11:49:24 -07001146 _exit(0);
1147 }
1148
1149 if (child == -1) {
1150 PLOG(ERROR) << "Failed to fork";
1151 goto next;
1152 } else {
1153 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1154 }
1155
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001156 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001157 close(nsFd);
1158 close(pidFd);
1159 }
1160 closedir(dir);
1161 return 0;
1162}
1163
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001164int VolumeManager::reset() {
1165 // Tear down all existing disks/volumes and start from a blank slate so
1166 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001167 if (mInternalEmulated != nullptr) {
1168 mInternalEmulated->destroy();
1169 mInternalEmulated->create();
1170 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001171 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001172 disk->destroy();
1173 disk->create();
1174 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001175 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001176 mAddedUsers.clear();
1177 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001178
1179 mUserPackages.clear();
1180 mAppIds.clear();
1181 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001182 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001183
1184 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001185 android::vold::UnmountTree("/mnt/user/");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001186 return 0;
1187}
1188
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001189// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001190int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001191 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001192 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001193 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001194 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001195 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001196 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001197 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001198 disk->destroy();
1199 }
Risan8c9f3322018-10-29 08:52:56 +09001200 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001201 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001202 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001203 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001204 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001205}
1206
Jeff Sharkey9c484982015-03-31 10:35:33 -07001207int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001208 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001209 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001210
Jeff Sharkey9c484982015-03-31 10:35:33 -07001211 // First, try gracefully unmounting all known devices
1212 if (mInternalEmulated != nullptr) {
1213 mInternalEmulated->unmount();
1214 }
Risan8c9f3322018-10-29 08:52:56 +09001215 for (const auto& stub : mStubVolumes) {
1216 stub->unmount();
1217 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001218 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001219 disk->unmountAll();
1220 }
1221
1222 // Worst case we might have some stale mounts lurking around, so
1223 // force unmount those just to be safe.
1224 FILE* fp = setmntent("/proc/mounts", "r");
1225 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001226 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001227 return -errno;
1228 }
1229
1230 // Some volumes can be stacked on each other, so force unmount in
1231 // reverse order to give us the best chance of success.
1232 std::list<std::string> toUnmount;
1233 mntent* mentry;
1234 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001235 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001236 if ((StartsWith(test, "/mnt/") &&
1237#ifdef __ANDROID_DEBUGGABLE__
1238 !StartsWith(test, "/mnt/scratch") &&
1239#endif
1240 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1241 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001242 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001243 }
1244 }
1245 endmntent(fp);
1246
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001247 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001248 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001249 android::vold::ForceUnmount(path);
1250 }
1251
1252 return 0;
1253}
1254
Jeff Sharkey3472e522017-10-06 18:02:53 -06001255int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001256 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001257 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001258 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001259 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001260 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001261 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001262 return -EINVAL;
1263 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001264}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001265
1266static size_t kAppFuseMaxMountPointName = 32;
1267
1268static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
1269 if (name.size() > kAppFuseMaxMountPointName) {
1270 LOG(ERROR) << "AppFuse mount name is too long.";
1271 return -EINVAL;
1272 }
1273 for (size_t i = 0; i < name.size(); i++) {
1274 if (!isalnum(name[i])) {
1275 LOG(ERROR) << "AppFuse mount name contains invalid character.";
1276 return -EINVAL;
1277 }
1278 }
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001279 *path = StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001280 return android::OK;
1281}
1282
Risan8f6198d2018-10-26 20:56:45 -06001283static android::status_t mount(int device_fd, const std::string& path) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001284 // Remove existing mount.
1285 android::vold::ForceUnmount(path);
1286
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001287 const auto opts = StringPrintf(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001288 "fd=%i,"
1289 "rootmode=40000,"
1290 "default_permissions,"
1291 "allow_other,"
Risan8f6198d2018-10-26 20:56:45 -06001292 "user_id=0,group_id=0,"
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001293 "context=\"u:object_r:app_fuse_file:s0\","
1294 "fscontext=u:object_r:app_fusefs:s0",
Risan8f6198d2018-10-26 20:56:45 -06001295 device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001296
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001297 const int result =
1298 TEMP_FAILURE_RETRY(mount("/dev/fuse", path.c_str(), "fuse",
1299 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001300 if (result != 0) {
1301 PLOG(ERROR) << "Failed to mount " << path;
1302 return -errno;
1303 }
1304
1305 return android::OK;
1306}
1307
Risan8f6198d2018-10-26 20:56:45 -06001308static android::status_t runCommand(const std::string& command, uid_t uid, const std::string& path,
1309 int device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001310 if (DEBUG_APPFUSE) {
Risan8f6198d2018-10-26 20:56:45 -06001311 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path << " and uid "
1312 << uid;
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001313 }
1314
Risan8f6198d2018-10-26 20:56:45 -06001315 if (command == "mount") {
1316 return mount(device_fd, path);
1317 } else if (command == "unmount") {
1318 // If it's just after all FD opened on mount point are closed, umount2 can fail with
1319 // EBUSY. To avoid the case, specify MNT_DETACH.
1320 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 && errno != EINVAL &&
1321 errno != ENOENT) {
1322 PLOG(ERROR) << "Failed to unmount directory.";
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001323 return -errno;
1324 }
Risan8f6198d2018-10-26 20:56:45 -06001325 if (rmdir(path.c_str()) != 0) {
1326 PLOG(ERROR) << "Failed to remove the mount directory.";
1327 return -errno;
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001328 }
Risan8f6198d2018-10-26 20:56:45 -06001329 return android::OK;
1330 } else {
1331 LOG(ERROR) << "Unknown appfuse command " << command;
1332 return -EPERM;
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001333 }
1334
Risan8f6198d2018-10-26 20:56:45 -06001335 return android::OK;
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001336}
1337
1338int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001339 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001340 int id = mNextObbId++;
1341
1342 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001343 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001344 vol->create();
1345
1346 mObbVolumes.push_back(vol);
1347 *outVolId = vol->getId();
1348 return android::OK;
1349}
1350
1351int VolumeManager::destroyObb(const std::string& volId) {
1352 auto i = mObbVolumes.begin();
1353 while (i != mObbVolumes.end()) {
1354 if ((*i)->getId() == volId) {
1355 (*i)->destroy();
1356 i = mObbVolumes.erase(i);
1357 } else {
1358 ++i;
1359 }
1360 }
1361 return android::OK;
1362}
1363
Risan8c9f3322018-10-29 08:52:56 +09001364int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1365 const std::string& fsType, const std::string& fsUuid,
1366 const std::string& fsLabel, std::string* outVolId) {
1367 int id = mNextStubVolumeId++;
1368 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1369 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1370 vol->create();
1371
1372 mStubVolumes.push_back(vol);
1373 *outVolId = vol->getId();
1374 return android::OK;
1375}
1376
1377int VolumeManager::destroyStubVolume(const std::string& volId) {
1378 auto i = mStubVolumes.begin();
1379 while (i != mStubVolumes.end()) {
1380 if ((*i)->getId() == volId) {
1381 (*i)->destroy();
1382 i = mStubVolumes.erase(i);
1383 } else {
1384 ++i;
1385 }
1386 }
1387 return android::OK;
1388}
1389
Risan8f6198d2018-10-26 20:56:45 -06001390int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001391 std::string name = std::to_string(mountId);
1392
1393 // Check mount point name.
1394 std::string path;
1395 if (getMountPath(uid, name, &path) != android::OK) {
1396 LOG(ERROR) << "Invalid mount point name";
1397 return -1;
1398 }
1399
1400 // Create directories.
1401 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
1402 if (result != android::OK) {
1403 PLOG(ERROR) << "Failed to prepare directory " << path;
1404 return -1;
1405 }
1406
1407 // Open device FD.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001408 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001409 if (device_fd->get() == -1) {
1410 PLOG(ERROR) << "Failed to open /dev/fuse";
1411 return -1;
1412 }
1413
1414 // Mount.
Risan8f6198d2018-10-26 20:56:45 -06001415 return runCommand("mount", uid, path, device_fd->get());
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001416}
1417
Risan8f6198d2018-10-26 20:56:45 -06001418int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001419 std::string name = std::to_string(mountId);
1420
1421 // Check mount point name.
1422 std::string path;
1423 if (getMountPath(uid, name, &path) != android::OK) {
1424 LOG(ERROR) << "Invalid mount point name";
1425 return -1;
1426 }
1427
Risan8f6198d2018-10-26 20:56:45 -06001428 return runCommand("unmount", uid, path, -1 /* device_fd */);
1429}
1430
1431int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
1432 std::string name = std::to_string(mountId);
1433
1434 // Check mount point name.
1435 std::string mountPoint;
1436 if (getMountPath(uid, name, &mountPoint) != android::OK) {
1437 LOG(ERROR) << "Invalid mount point name";
1438 return -1;
1439 }
1440
1441 std::string path = StringPrintf("%s/%d", mountPoint.c_str(), fileId);
1442 return TEMP_FAILURE_RETRY(open(path.c_str(), flags));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001443}