blob: d38052ddd40b899deecabf6af2af5f13a065d3fd [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
Paul Crowleyc6433a22017-10-24 14:54:43 -070052#include <ext4_utils/ext4_crypt.h>
53
54#include "Devmapper.h"
55#include "Ext4Crypt.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"
San Mehat23969932010-01-09 07:08:06 -080068
Sudheer Shanka53947a32018-08-01 10:24:13 -070069using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070070using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070071using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070072using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060073using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070074
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060075static const char* kPathUserMount = "/mnt/user";
76static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
77
Sudheer Shanka53947a32018-08-01 10:24:13 -070078static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060079static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
80
Sudheer Shanka53947a32018-08-01 10:24:13 -070081static const std::string kEmptyString("");
82
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060083/* 512MiB is large enough for testing purposes */
84static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070085
Jeff Sharkey36801cc2015-03-13 16:09:20 -070086static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080087static const unsigned int kMajorBlockExperimentalMin = 240;
88static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070089
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070090VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070091
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070092VolumeManager* VolumeManager::Instance() {
93 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070094 return sInstance;
95}
96
97VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080098 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060099 mNextObbId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700100 // For security reasons, assume that a secure keyguard is
101 // showing until we hear otherwise
102 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700103}
104
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700105VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800106
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600107int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600108 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700109 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600110 if (access(kPathVirtualDisk, F_OK) != 0) {
111 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
112 }
113
114 if (mVirtualDisk == nullptr) {
115 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
116 LOG(ERROR) << "Failed to create virtual disk";
117 return -1;
118 }
119
120 struct stat buf;
121 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
122 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
123 return -1;
124 }
125
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700126 auto disk = new android::vold::Disk(
127 "virtual", buf.st_rdev, "virtual",
128 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700130 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600131 }
132 } else {
133 if (mVirtualDisk != nullptr) {
134 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700135 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600136
137 Loop::destroyByDevice(mVirtualDiskPath.c_str());
138 mVirtualDisk = nullptr;
139 }
140
141 if (access(kPathVirtualDisk, F_OK) == 0) {
142 unlink(kPathVirtualDisk);
143 }
144 }
145 return 0;
146}
147
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700148int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800149 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700150 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800151}
152
San Mehatf1b736b2009-10-10 17:22:08 -0700153int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600154 ATRACE_NAME("VolumeManager::start");
155
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700156 // Always start from a clean slate by unmounting everything in
157 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700158 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700159
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600160 Devmapper::destroyAll();
161 Loop::destroyAll();
162
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700163 // Assume that we always have an emulated volume on internal
164 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700165 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700166 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700167 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700168 mInternalEmulated->create();
169
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600170 // Consider creating a virtual disk
171 updateVirtualDisk();
172
San Mehatf1b736b2009-10-10 17:22:08 -0700173 return 0;
174}
175
176int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700177 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700178 mInternalEmulated->destroy();
179 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700180 return 0;
181}
182
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700183void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700184 std::lock_guard<std::mutex> lock(mLock);
185
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700186 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700187 LOG(DEBUG) << "----------------";
188 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700189 evt->dump();
190 }
San Mehatf1b736b2009-10-10 17:22:08 -0700191
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700192 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
193 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194
195 if (devType != "disk") return;
196
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600197 int major = std::stoi(evt->findParam("MAJOR"));
198 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700199 dev_t device = makedev(major, minor);
200
201 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700202 case NetlinkEvent::Action::kAdd: {
203 for (const auto& source : mDiskSources) {
204 if (source->matches(eventPath)) {
205 // For now, assume that MMC and virtio-blk (the latter is
206 // emulator-specific; see Disk.cpp for details) devices are SD,
207 // and that everything else is USB
208 int flags = source->getFlags();
209 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
210 major >= (int)kMajorBlockExperimentalMin &&
211 major <= (int)kMajorBlockExperimentalMax)) {
212 flags |= android::vold::Disk::Flags::kSd;
213 } else {
214 flags |= android::vold::Disk::Flags::kUsb;
215 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700216
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700217 auto disk =
218 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
219 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
220 break;
221 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700222 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700223 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700224 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700225 case NetlinkEvent::Action::kChange: {
226 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
227 handleDiskChanged(device);
228 break;
229 }
230 case NetlinkEvent::Action::kRemove: {
231 handleDiskRemoved(device);
232 break;
233 }
234 default: {
235 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
236 break;
237 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700238 }
239}
240
Jeff Sharkey401b2602017-12-14 22:15:20 -0700241void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
242 // For security reasons, if secure keyguard is showing, wait
243 // until the user unlocks the device to actually touch it
244 if (mSecureKeyguardShowing) {
245 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700246 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700247 mPendingDisks.push_back(disk);
248 } else {
249 disk->create();
250 mDisks.push_back(disk);
251 }
252}
253
254void VolumeManager::handleDiskChanged(dev_t device) {
255 for (const auto& disk : mDisks) {
256 if (disk->getDevice() == device) {
257 disk->readMetadata();
258 disk->readPartitions();
259 }
260 }
261
262 // For security reasons, we ignore all pending disks, since
263 // we'll scan them once the device is unlocked
264}
265
266void VolumeManager::handleDiskRemoved(dev_t device) {
267 auto i = mDisks.begin();
268 while (i != mDisks.end()) {
269 if ((*i)->getDevice() == device) {
270 (*i)->destroy();
271 i = mDisks.erase(i);
272 } else {
273 ++i;
274 }
275 }
276 auto j = mPendingDisks.begin();
277 while (j != mPendingDisks.end()) {
278 if ((*j)->getDevice() == device) {
279 j = mPendingDisks.erase(j);
280 } else {
281 ++j;
282 }
283 }
284}
285
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700286void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800287 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700288 mDiskSources.push_back(diskSource);
289}
290
291std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
292 for (auto disk : mDisks) {
293 if (disk->getId() == id) {
294 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700295 }
296 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700297 return nullptr;
298}
San Mehatf1b736b2009-10-10 17:22:08 -0700299
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700300std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800301 // Vold could receive "mount" after "shutdown" command in the extreme case.
302 // If this happens, mInternalEmulated will equal nullptr and
303 // we need to deal with it in order to avoid null pointer crash.
304 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700305 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700306 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700307 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700308 auto vol = disk->findVolume(id);
309 if (vol != nullptr) {
310 return vol;
311 }
312 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600313 for (const auto& vol : mObbVolumes) {
314 if (vol->getId() == id) {
315 return vol;
316 }
317 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318 return nullptr;
319}
320
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700321void VolumeManager::listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700322 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 Shanka40ab6742018-09-18 13:07:45 -0700349int VolumeManager::linkPrimary(userid_t userId) {
350 std::string source(mPrimary->getPath());
351 if (mPrimary->isEmulated()) {
352 source = StringPrintf("%s/%d", source.c_str(), userId);
353 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
354 }
355
356 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
357 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
358 if (errno != ENOENT) {
359 PLOG(WARNING) << "Failed to unlink " << target;
360 }
361 }
362 LOG(DEBUG) << "Linking " << source << " to " << target;
363 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
364 PLOG(WARNING) << "Failed to link";
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700365 return -errno;
366 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700367 return 0;
368}
369
370int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
371 const std::string& mntTargetRoot,
372 const std::string& packageName, const char* dirName) {
373 std::string mntSourceDir =
374 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
375 std::string mntTargetDir =
376 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
377 if (umount2(mntTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL && errno != ENOENT) {
378 PLOG(ERROR) << "Failed to unmount " << mntTargetDir;
379 return -1;
380 }
381 if (TEMP_FAILURE_RETRY(mount(mntSourceDir.c_str(), mntTargetDir.c_str(), nullptr,
382 MS_BIND | MS_REC, nullptr)) == -1) {
383 PLOG(ERROR) << "Failed to mount " << mntSourceDir << " to " << mntTargetDir;
384 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700385 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700386 if (TEMP_FAILURE_RETRY(
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700387 mount(nullptr, mntTargetDir.c_str(), nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
388 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTargetDir;
389 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700390 }
391 return 0;
392}
393
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700394int VolumeManager::mountPkgSpecificDirsForRunningProcs(
395 userid_t userId, const std::vector<std::string>& packageNames,
396 const std::vector<std::string>& visibleVolLabels) {
397 // TODO: New processes could be started while traversing over the existing
398 // processes which would end up not having the necessary bind mounts. This
399 // issue needs to be fixed, may be by doing multiple passes here?
400 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
401 if (!dirp) {
402 PLOG(ERROR) << "Failed to opendir /proc";
403 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700404 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700405
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700406 std::string rootName;
407 // Figure out root namespace to compare against below
408 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
409 PLOG(ERROR) << "Failed to read root namespace";
410 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700411 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700412
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700413 struct stat fullWriteSb;
414 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &fullWriteSb)) == -1) {
415 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
416 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700417 }
418
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700419 std::unordered_set<appid_t> validAppIds;
420 for (auto& package : packageNames) {
421 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700422 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700423 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700424
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700425 struct dirent* de;
426 // Poke through all running PIDs look for apps running in userId
427 while ((de = readdir(dirp.get()))) {
428 pid_t pid;
429 if (de->d_type != DT_DIR) continue;
430 if (!android::base::ParseInt(de->d_name, &pid)) continue;
431
432 const unique_fd pidFd(
433 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
434 if (pidFd.get() < 0) {
435 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700436 continue;
437 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700438 struct stat sb;
439 if (fstat(pidFd.get(), &sb) != 0) {
440 PLOG(WARNING) << "Failed to stat " << de->d_name;
441 continue;
442 }
443 if (multiuser_get_user_id(sb.st_uid) != userId) {
444 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700445 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700446
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700447 // Matches so far, but refuse to touch if in root namespace
448 LOG(VERBOSE) << "Found matching PID " << de->d_name;
449 std::string pidName;
450 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
451 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
452 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700453 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700454 if (rootName == pidName) {
455 LOG(WARNING) << "Skipping due to root namespace";
456 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700457 }
458
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700459 // Only update the mount points of processes running with one of validAppIds.
460 // This should skip any isolated uids.
461 appid_t appId = multiuser_get_app_id(sb.st_uid);
462 if (validAppIds.find(appId) == validAppIds.end()) {
463 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700464 }
465
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700466 std::vector<std::string> packagesForUid;
467 for (auto& package : userPackages) {
468 if (mAppIds[package] == appId) {
469 packagesForUid.push_back(package);
470 }
471 }
472 if (packagesForUid.empty()) {
473 continue;
474 }
475 const std::string& sandboxId = mSandboxIds[appId];
476
477 // We purposefully leave the namespace open across the fork
478 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
479 if (nsFd.get() < 0) {
480 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
481 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700482 }
483
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700484 pid_t child;
485 if (!(child = fork())) {
486 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
487 PLOG(ERROR) << "Failed to setns for " << de->d_name;
488 _exit(1);
489 }
490
491 struct stat storageSb;
492 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
493 PLOG(ERROR) << "Failed to stat /storage";
494 _exit(1);
495 }
496
497 // Some packages have access to full external storage, identify processes belonging
498 // to those packages by comparing inode no.s of /mnt/runtime/write and /storage
499 if (storageSb.st_dev == fullWriteSb.st_dev && storageSb.st_ino == fullWriteSb.st_ino) {
500 _exit(0);
501 } else {
502 // Some packages don't have access to external storage and processes belonging to
503 // those packages don't have anything mounted at /storage. So, identify those
504 // processes by comparing inode no.s of /mnt/user/%d/package/%s
505 // and /storage
506 std::string pkgStorageSource;
507 for (auto& package : packagesForUid) {
508 std::string sandbox =
509 StringPrintf("/mnt/user/%d/package/%s", userId, package.c_str());
510 struct stat s;
511 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &s)) == -1) {
512 PLOG(ERROR) << "Failed to stat " << sandbox;
513 _exit(1);
514 }
515 if (storageSb.st_dev == s.st_dev && storageSb.st_ino == s.st_ino) {
516 pkgStorageSource = sandbox;
517 break;
518 }
519 }
520 if (pkgStorageSource.empty()) {
521 _exit(0);
522 }
523 }
524
525 for (auto& volumeLabel : visibleVolLabels) {
526 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
527 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
528 if (volumeLabel == "emulated") {
529 StringAppendF(&mntSource, "/%d", userId);
530 StringAppendF(&mntTarget, "/%d", userId);
531 }
532 for (auto& package : packagesForUid) {
533 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
534 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
535 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
536 }
537 }
538 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700539 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700540
541 if (child == -1) {
542 PLOG(ERROR) << "Failed to fork";
543 } else {
544 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700545 }
546 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700547 return 0;
548}
549
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700550int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
551 const std::vector<std::string>& visibleVolLabels) {
552 if (visibleVolLabels.empty()) {
553 return 0;
554 }
555 for (auto& volumeLabel : visibleVolLabels) {
556 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
557 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
558 if (isVolPrimaryEmulated) {
559 StringAppendF(&volumeRoot, "/%d", userId);
560 if (fs_prepare_dir(volumeRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
561 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeRoot;
562 return -errno;
563 }
564 }
565
566 std::string sandboxRoot =
567 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
568 if (sandboxRoot.empty()) {
569 return -errno;
570 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700571
572 if (!createPkgSpecificDirRoots(volumeRoot)) {
573 return -errno;
574 }
575
576 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
577 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
578 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
579 return -errno;
580 }
581 mntTargetRoot.append("/package");
582 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
583 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
584 return -errno;
585 }
586
587 for (auto& packageName : packageNames) {
588 const auto& it = mAppIds.find(packageName);
589 if (it == mAppIds.end()) {
590 PLOG(ERROR) << "appId is not available for " << packageName;
591 continue;
592 }
593 appid_t appId = it->second;
594 std::string sandboxId = mSandboxIds[appId];
595 uid_t uid = multiuser_get_uid(userId, appId);
596
597 // [1] Create /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
598 // [2] Create /mnt/user/0/package/<packageName>/emulated/0
599 // Mount [1] at [2]
600 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
601 if (pkgSandboxSourceDir.empty()) {
602 return -errno;
603 }
604 std::string pkgSandboxTargetDir = prepareSandboxTarget(
605 packageName, uid, volumeLabel, mntTargetRoot, isVolPrimaryEmulated);
606 if (pkgSandboxTargetDir.empty()) {
607 return -errno;
608 }
609 if (umount2(pkgSandboxTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
610 errno != ENOENT) {
611 PLOG(ERROR) << "Failed to unmount " << pkgSandboxTargetDir;
612 return -errno;
613 }
614 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
615 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
616 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
617 << pkgSandboxTargetDir;
618 return -errno;
619 }
620 if (TEMP_FAILURE_RETRY(mount(nullptr, pkgSandboxTargetDir.c_str(), nullptr,
621 MS_SLAVE | MS_REC, nullptr)) == -1) {
622 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
623 << pkgSandboxTargetDir;
624 return -errno;
625 }
626
627 // Create Android/{data,media,obb}/<packageName> segments at
628 // [1] /mnt/runtime/write/emulated/0/ and
629 // [2] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>/emulated/0/
630 if (!createPkgSpecificDirs(packageName, uid, volumeRoot, pkgSandboxSourceDir)) {
631 return -errno;
632 }
633
634 if (volumeLabel == mPrimary->getLabel()) {
635 // Create [1] /mnt/user/0/package/<packageName>/self/
636 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
637 // Mount [2] at [1]
638 std::string pkgPrimaryTargetDir =
639 StringPrintf("%s/%s/self", mntTargetRoot.c_str(), packageName.c_str());
640 if (fs_prepare_dir(pkgPrimaryTargetDir.c_str(), 0755, uid, uid) != 0) {
641 PLOG(ERROR) << "Failed to fs_prepare_dir on " << pkgPrimaryTargetDir;
642 return -errno;
643 }
644 StringAppendF(&pkgPrimaryTargetDir, "/primary");
645 std::string primarySource(mPrimary->getPath());
646 if (isVolPrimaryEmulated) {
647 StringAppendF(&primarySource, "/%d", userId);
648 }
649 if (TEMP_FAILURE_RETRY(unlink(pkgPrimaryTargetDir.c_str()))) {
650 if (errno != ENOENT) {
651 PLOG(ERROR) << "Failed to unlink " << pkgPrimaryTargetDir;
652 }
653 }
654 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), pkgPrimaryTargetDir.c_str()))) {
655 PLOG(ERROR) << "Failed to link " << primarySource << " at "
656 << pkgPrimaryTargetDir;
657 return -errno;
658 }
659 }
660 }
661 }
662 mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels);
663 return 0;
664}
665
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700666std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
667 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700668 std::string path(pathPrefix);
669 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
670 for (size_t i = 0; i < subDirList.size(); ++i) {
671 std::string subDir = subDirList[i];
672 if (subDir.empty()) {
673 continue;
674 }
675 StringAppendF(&path, "/%s", subDir.c_str());
676 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
677 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
678 return kEmptyString;
679 }
680 }
681 return path;
682}
683
684std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700685 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700686 std::string sandboxSourceDir(sandboxRootDir);
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700687 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700688 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
689 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
690 return kEmptyString;
691 }
692 return sandboxSourceDir;
693}
694
695std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700696 const std::string& volumeLabel,
697 const std::string& mntTargetRootDir,
698 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700699 std::string segment;
700 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700701 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
702 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700703 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700704 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700705 }
706 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
707}
708
709std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700710 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700711 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
712 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
713 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
714 return kEmptyString;
715 }
716 return dataSourceDir;
717}
718
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700719bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
720 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
721 if (fs_prepare_dir(volumeAndroidRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
722 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeAndroidRoot;
723 return false;
724 }
725 std::array<std::string, 3> dirs = {"data", "media", "obb"};
726 for (auto& dir : dirs) {
727 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
728 if (fs_prepare_dir(path.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
729 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
730 return false;
731 }
732 }
733 return true;
734}
735
736bool VolumeManager::createPkgSpecificDirs(const std::string& packageName, uid_t uid,
737 const std::string& volumeRoot,
738 const std::string& sandboxDirRoot) {
739 std::array<std::string, 3> dirs = {"data", "media", "obb"};
740 for (auto& dir : dirs) {
741 std::string sourceDir = StringPrintf("%s/Android/%s", volumeRoot.c_str(), dir.c_str());
742 if (prepareSubDirs(sourceDir, packageName, 0755, uid, uid).empty()) {
743 return false;
744 }
745 std::string sandboxSegment =
746 StringPrintf("Android/%s/%s/", dir.c_str(), packageName.c_str());
747 if (prepareSubDirs(sandboxDirRoot, sandboxSegment, 0755, uid, uid).empty()) {
748 return false;
749 }
750 }
751 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700752}
753
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700754int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
755 mAddedUsers[userId] = userSerialNumber;
756 return 0;
757}
758
759int VolumeManager::onUserRemoved(userid_t userId) {
760 mAddedUsers.erase(userId);
761 return 0;
762}
763
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700764int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
765 const std::vector<int>& appIds,
766 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700767 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700768 // Note that sometimes the system will spin up processes from Zygote
769 // before actually starting the user, so we're okay if Zygote
770 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600771 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700772 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
773
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700774 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700775 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700776 for (size_t i = 0; i < packageNames.size(); ++i) {
777 mAppIds[packageNames[i]] = appIds[i];
778 mSandboxIds[appIds[i]] = sandboxIds[i];
779 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700780 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700781 linkPrimary(userId);
782 }
783 if (GetBoolProperty(kIsolatedStorage, false)) {
784 std::vector<std::string> visibleVolLabels;
785 for (auto& volId : mVisibleVolumeIds) {
786 auto vol = findVolume(volId);
787 userid_t mountUserId = vol->getMountUserId();
788 if (mountUserId == userId || vol->isEmulated()) {
789 visibleVolLabels.push_back(vol->getLabel());
790 }
791 }
792 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
793 return -errno;
794 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700795 }
796 return 0;
797}
798
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700799int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700800 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700801 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700802
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700803 if (GetBoolProperty(kIsolatedStorage, false)) {
804 mUserPackages.erase(userId);
805 std::string mntTargetDir = StringPrintf("/mnt/user/%d", userId);
806 if (android::vold::UnmountTree(mntTargetDir) != 0) {
807 PLOG(ERROR) << "unmountTree on " << mntTargetDir << " failed";
808 return -errno;
809 }
810 if (android::vold::DeleteDirContentsAndDir(mntTargetDir) < 0) {
811 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << mntTargetDir;
812 return -errno;
813 }
814 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << mntTargetDir;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700815 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700816 return 0;
817}
818
Sudheer Shankad484aa92018-07-31 10:07:34 -0700819int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700820 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700821 for (size_t i = 0; i < packageNames.size(); ++i) {
822 mAppIds[packageNames[i]] = appIds[i];
823 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700824 return 0;
825}
826
827int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700828 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700829 for (size_t i = 0; i < appIds.size(); ++i) {
830 mSandboxIds[appIds[i]] = sandboxIds[i];
831 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700832 return 0;
833}
834
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700835int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
836 const std::string& sandboxId, userid_t userId) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700837 if (!GetBoolProperty(kIsolatedStorage, false)) {
838 return 0;
839 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
840 // User not started, no need to do anything now. Required bind mounts for the package will
841 // be created when the user starts.
842 return 0;
843 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700844 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700845 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700846 mUserPackages[userId].push_back(packageName);
847 mAppIds[packageName] = appId;
848 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700849
850 std::vector<std::string> visibleVolLabels;
851 for (auto& volId : mVisibleVolumeIds) {
852 auto vol = findVolume(volId);
853 userid_t mountUserId = vol->getMountUserId();
854 if (mountUserId == userId || vol->isEmulated()) {
855 visibleVolLabels.push_back(vol->getLabel());
856 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700857 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700858 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700859}
860
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700861int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700862 const std::string& sandboxId, userid_t userId) {
863 if (!GetBoolProperty(kIsolatedStorage, false)) {
864 return 0;
865 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700866 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
867 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700868 auto& userPackages = mUserPackages[userId];
869 std::remove(userPackages.begin(), userPackages.end(), packageName);
870 // If the package is not uninstalled in any other users, remove appId and sandboxId
871 // corresponding to it from the internal state.
872 bool installedInAnyUser = false;
873 for (auto& it : mUserPackages) {
874 auto& packages = it.second;
875 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
876 installedInAnyUser = true;
877 break;
878 }
879 }
880 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700881 const auto& entry = mAppIds.find(packageName);
882 if (entry != mAppIds.end()) {
883 mSandboxIds.erase(entry->second);
884 mAppIds.erase(entry);
885 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700886 }
887
888 std::vector<std::string> visibleVolLabels;
889 for (auto& volId : mVisibleVolumeIds) {
890 auto vol = findVolume(volId);
891 userid_t mountUserId = vol->getMountUserId();
892 if (mountUserId == userId || vol->isEmulated()) {
893 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
894 return -errno;
895 }
896 }
897 }
898 return 0;
899}
900
901int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
902 const std::string& sandboxId, userid_t userId,
903 const std::string& volLabel) {
904 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
905 << ", volLabel=" << volLabel;
906 std::string pkgSandboxTarget =
907 StringPrintf("/mnt/user/%d/package/%s", userId, packageName.c_str());
908 if (android::vold::UnmountTree(pkgSandboxTarget)) {
909 PLOG(ERROR) << "UnmountTree failed on " << pkgSandboxTarget;
910 }
911
912 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
913 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
914 StringAppendF(&sandboxDir, "/%d", userId);
915 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700916 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700917
918 if (android::vold::DeleteDirContentsAndDir(sandboxDir) < 0) {
919 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
920 return -errno;
921 }
922 return 0;
923}
924
Jeff Sharkey401b2602017-12-14 22:15:20 -0700925int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
926 mSecureKeyguardShowing = isShowing;
927 if (!mSecureKeyguardShowing) {
928 // Now that secure keyguard has been dismissed, process
929 // any pending disks
930 for (const auto& disk : mPendingDisks) {
931 disk->create();
932 mDisks.push_back(disk);
933 }
934 mPendingDisks.clear();
935 }
936 return 0;
937}
938
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700939int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
940 if (!GetBoolProperty(kIsolatedStorage, false)) {
941 return 0;
942 }
943
944 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
945 return 0;
946 }
947
948 mVisibleVolumeIds.insert(vol->getId());
949 userid_t mountUserId = vol->getMountUserId();
950 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
951 // We don't want to create another shared_ptr here because then we will end up with
952 // two shared_ptrs owning the underlying pointer without sharing it.
953 mPrimary = findVolume(vol->getId());
954 for (userid_t userId : mStartedUsers) {
955 if (linkPrimary(userId) != 0) {
956 return -errno;
957 }
958 }
959 }
960 if (vol->isEmulated()) {
961 for (userid_t userId : mStartedUsers) {
962 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
963 return -errno;
964 }
965 }
966 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
967 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
968 return -errno;
969 }
970 }
971 return 0;
972}
973
974int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
975 if (!GetBoolProperty(kIsolatedStorage, false)) {
976 return 0;
977 }
978
979 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
980 return 0;
981 }
982
983 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
984 mPrimary = nullptr;
985 }
986
987 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
988 userid_t mountUserId = vol->getMountUserId();
989 if (vol->isEmulated()) {
990 for (userid_t userId : mStartedUsers) {
991 if (destroySandboxesForVol(vol, userId) != 0) {
992 return -errno;
993 }
994 }
995 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
996 if (destroySandboxesForVol(vol, mountUserId) != 0) {
997 return -errno;
998 }
999 }
1000 return 0;
1001}
1002
1003int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1004 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
1005 const std::vector<std::string>& packageNames = mUserPackages[userId];
1006 for (auto& packageName : packageNames) {
1007 std::string volSandboxRoot = StringPrintf("/mnt/user/%d/package/%s/%s", userId,
1008 packageName.c_str(), vol->getLabel().c_str());
1009 if (android::vold::UnmountTree(volSandboxRoot) != 0) {
1010 PLOG(ERROR) << "unmountTree on " << volSandboxRoot << " failed";
1011 continue;
1012 }
1013 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1014 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1015 continue;
1016 }
1017 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
1018 }
1019 return 0;
1020}
1021
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001022int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001023 if (GetBoolProperty(kIsolatedStorage, false)) {
1024 return 0;
1025 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001026 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001027 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001028 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001029 }
1030 return 0;
1031}
1032
Jeff Sharkey66270a22015-06-24 11:49:24 -07001033int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
Sudheer Shanka53947a32018-08-01 10:24:13 -07001034 // If the isolated storage is enabled, return -1 since in the isolated storage world, there
1035 // are no longer any runtime storage permissions, so this shouldn't be called anymore.
1036 if (GetBoolProperty(kIsolatedStorage, false)) {
1037 return -1;
1038 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001039 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1040
1041 DIR* dir;
1042 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001043 std::string rootName;
1044 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001045 int pidFd;
1046 int nsFd;
1047 struct stat sb;
1048 pid_t child;
1049
1050 if (!(dir = opendir("/proc"))) {
1051 PLOG(ERROR) << "Failed to opendir";
1052 return -1;
1053 }
1054
1055 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001056 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1057 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001058 closedir(dir);
1059 return -1;
1060 }
1061
1062 // Poke through all running PIDs look for apps running as UID
1063 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001064 pid_t pid;
1065 if (de->d_type != DT_DIR) continue;
1066 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1067
Jeff Sharkey66270a22015-06-24 11:49:24 -07001068 pidFd = -1;
1069 nsFd = -1;
1070
1071 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1072 if (pidFd < 0) {
1073 goto next;
1074 }
1075 if (fstat(pidFd, &sb) != 0) {
1076 PLOG(WARNING) << "Failed to stat " << de->d_name;
1077 goto next;
1078 }
1079 if (sb.st_uid != uid) {
1080 goto next;
1081 }
1082
1083 // Matches so far, but refuse to touch if in root namespace
1084 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001085 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001086 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1087 goto next;
1088 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001089 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001090 LOG(WARNING) << "Skipping due to root namespace";
1091 goto next;
1092 }
1093
1094 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001095 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -07001096 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001097 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001098 goto next;
1099 }
1100
1101 if (!(child = fork())) {
1102 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001103 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001104 _exit(1);
1105 }
1106
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001107 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001108
1109 std::string storageSource;
1110 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001111 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001112 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001113 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001114 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001115 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001116 } else {
1117 // Sane default of no storage visible
1118 _exit(0);
1119 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001120 if (TEMP_FAILURE_RETRY(
1121 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1122 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001123 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001124 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001125 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1126 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001127 _exit(1);
1128 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001129
1130 // Mount user-specific symlink helper into place
1131 userid_t user_id = multiuser_get_user_id(uid);
1132 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001133 if (TEMP_FAILURE_RETRY(
1134 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1135 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001136 _exit(1);
1137 }
1138
Jeff Sharkey66270a22015-06-24 11:49:24 -07001139 _exit(0);
1140 }
1141
1142 if (child == -1) {
1143 PLOG(ERROR) << "Failed to fork";
1144 goto next;
1145 } else {
1146 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1147 }
1148
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001149 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001150 close(nsFd);
1151 close(pidFd);
1152 }
1153 closedir(dir);
1154 return 0;
1155}
1156
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001157int VolumeManager::reset() {
1158 // Tear down all existing disks/volumes and start from a blank slate so
1159 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001160 if (mInternalEmulated != nullptr) {
1161 mInternalEmulated->destroy();
1162 mInternalEmulated->create();
1163 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001164 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001165 disk->destroy();
1166 disk->create();
1167 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001168 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001169 mAddedUsers.clear();
1170 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001171
1172 mUserPackages.clear();
1173 mAppIds.clear();
1174 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001175 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001176
1177 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001178 android::vold::UnmountTree("/mnt/user/");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001179 return 0;
1180}
1181
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001182// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001183int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001184 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001185 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001186 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001187 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001188 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001189 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001190 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001191 disk->destroy();
1192 }
1193 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001194 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001195 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001196 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001197}
1198
Jeff Sharkey9c484982015-03-31 10:35:33 -07001199int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001200 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001201 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001202
Jeff Sharkey9c484982015-03-31 10:35:33 -07001203 // First, try gracefully unmounting all known devices
1204 if (mInternalEmulated != nullptr) {
1205 mInternalEmulated->unmount();
1206 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001207 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001208 disk->unmountAll();
1209 }
1210
1211 // Worst case we might have some stale mounts lurking around, so
1212 // force unmount those just to be safe.
1213 FILE* fp = setmntent("/proc/mounts", "r");
1214 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001215 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001216 return -errno;
1217 }
1218
1219 // Some volumes can be stacked on each other, so force unmount in
1220 // reverse order to give us the best chance of success.
1221 std::list<std::string> toUnmount;
1222 mntent* mentry;
1223 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001224 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001225 if ((StartsWith(test, "/mnt/") &&
1226#ifdef __ANDROID_DEBUGGABLE__
1227 !StartsWith(test, "/mnt/scratch") &&
1228#endif
1229 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1230 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001231 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001232 }
1233 }
1234 endmntent(fp);
1235
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001236 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001237 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001238 android::vold::ForceUnmount(path);
1239 }
1240
1241 return 0;
1242}
1243
Jeff Sharkey3472e522017-10-06 18:02:53 -06001244int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001245 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001246 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001247 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001248 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001249 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001250 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001251 return -EINVAL;
1252 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001253}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001254
1255static size_t kAppFuseMaxMountPointName = 32;
1256
1257static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
1258 if (name.size() > kAppFuseMaxMountPointName) {
1259 LOG(ERROR) << "AppFuse mount name is too long.";
1260 return -EINVAL;
1261 }
1262 for (size_t i = 0; i < name.size(); i++) {
1263 if (!isalnum(name[i])) {
1264 LOG(ERROR) << "AppFuse mount name contains invalid character.";
1265 return -EINVAL;
1266 }
1267 }
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001268 *path = StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001269 return android::OK;
1270}
1271
1272static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
1273 // Remove existing mount.
1274 android::vold::ForceUnmount(path);
1275
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001276 const auto opts = StringPrintf(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001277 "fd=%i,"
1278 "rootmode=40000,"
1279 "default_permissions,"
1280 "allow_other,"
1281 "user_id=%d,group_id=%d,"
1282 "context=\"u:object_r:app_fuse_file:s0\","
1283 "fscontext=u:object_r:app_fusefs:s0",
1284 device_fd, uid, uid);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001285
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001286 const int result =
1287 TEMP_FAILURE_RETRY(mount("/dev/fuse", path.c_str(), "fuse",
1288 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001289 if (result != 0) {
1290 PLOG(ERROR) << "Failed to mount " << path;
1291 return -errno;
1292 }
1293
1294 return android::OK;
1295}
1296
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001297static android::status_t runCommandInNamespace(const std::string& command, uid_t uid, pid_t pid,
1298 const std::string& path, int device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001299 if (DEBUG_APPFUSE) {
1300 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
1301 << " in namespace " << uid;
1302 }
1303
1304 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
1305 if (dir.get() == -1) {
1306 PLOG(ERROR) << "Failed to open /proc";
1307 return -errno;
1308 }
1309
1310 // Obtains process file descriptor.
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001311 const std::string pid_str = StringPrintf("%d", pid);
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001312 const unique_fd pid_fd(openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001313 if (pid_fd.get() == -1) {
1314 PLOG(ERROR) << "Failed to open /proc/" << pid;
1315 return -errno;
1316 }
1317
1318 // Check UID of process.
1319 {
1320 struct stat sb;
1321 const int result = fstat(pid_fd.get(), &sb);
1322 if (result == -1) {
1323 PLOG(ERROR) << "Failed to stat /proc/" << pid;
1324 return -errno;
1325 }
1326 if (sb.st_uid != AID_SYSTEM) {
1327 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001328 << ", actual=" << sb.st_uid;
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001329 return -EPERM;
1330 }
1331 }
1332
1333 // Matches so far, but refuse to touch if in root namespace
1334 {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001335 std::string rootName;
1336 std::string pidName;
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001337 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName) ||
1338 !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001339 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001340 return -EPERM;
1341 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001342 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001343 LOG(ERROR) << "Don't mount appfuse in root namespace";
1344 return -EPERM;
1345 }
1346 }
1347
1348 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001349 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001350 if (ns_fd.get() < 0) {
1351 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
1352 return -errno;
1353 }
1354
1355 int child = fork();
1356 if (child == 0) {
1357 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
1358 PLOG(ERROR) << "Failed to setns";
1359 _exit(-errno);
1360 }
1361
1362 if (command == "mount") {
1363 _exit(mountInNamespace(uid, device_fd, path));
1364 } else if (command == "unmount") {
1365 // If it's just after all FD opened on mount point are closed, umount2 can fail with
1366 // EBUSY. To avoid the case, specify MNT_DETACH.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001367 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 && errno != EINVAL &&
1368 errno != ENOENT) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001369 PLOG(ERROR) << "Failed to unmount directory.";
1370 _exit(-errno);
1371 }
1372 if (rmdir(path.c_str()) != 0) {
1373 PLOG(ERROR) << "Failed to remove the mount directory.";
1374 _exit(-errno);
1375 }
1376 _exit(android::OK);
1377 } else {
1378 LOG(ERROR) << "Unknown appfuse command " << command;
1379 _exit(-EPERM);
1380 }
1381 }
1382
1383 if (child == -1) {
1384 PLOG(ERROR) << "Failed to folk child process";
1385 return -errno;
1386 }
1387
1388 android::status_t status;
1389 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
1390
1391 return status;
1392}
1393
1394int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001395 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001396 int id = mNextObbId++;
1397
1398 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001399 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001400 vol->create();
1401
1402 mObbVolumes.push_back(vol);
1403 *outVolId = vol->getId();
1404 return android::OK;
1405}
1406
1407int VolumeManager::destroyObb(const std::string& volId) {
1408 auto i = mObbVolumes.begin();
1409 while (i != mObbVolumes.end()) {
1410 if ((*i)->getId() == volId) {
1411 (*i)->destroy();
1412 i = mObbVolumes.erase(i);
1413 } else {
1414 ++i;
1415 }
1416 }
1417 return android::OK;
1418}
1419
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001420int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId, unique_fd* device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001421 std::string name = std::to_string(mountId);
1422
1423 // Check mount point name.
1424 std::string path;
1425 if (getMountPath(uid, name, &path) != android::OK) {
1426 LOG(ERROR) << "Invalid mount point name";
1427 return -1;
1428 }
1429
1430 // Create directories.
1431 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
1432 if (result != android::OK) {
1433 PLOG(ERROR) << "Failed to prepare directory " << path;
1434 return -1;
1435 }
1436
1437 // Open device FD.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001438 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001439 if (device_fd->get() == -1) {
1440 PLOG(ERROR) << "Failed to open /dev/fuse";
1441 return -1;
1442 }
1443
1444 // Mount.
1445 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
1446}
1447
1448int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
1449 std::string name = std::to_string(mountId);
1450
1451 // Check mount point name.
1452 std::string path;
1453 if (getMountPath(uid, name, &path) != android::OK) {
1454 LOG(ERROR) << "Invalid mount point name";
1455 return -1;
1456 }
1457
1458 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
1459}