blob: 20cc5eccb52fc27e1dbdb24b13ce9f9577218efb [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;
70using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070071using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060072using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070073
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060074static const char* kPathUserMount = "/mnt/user";
75static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
76
Sudheer Shanka53947a32018-08-01 10:24:13 -070077static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060078static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
79
Sudheer Shanka53947a32018-08-01 10:24:13 -070080static const std::string kEmptyString("");
81
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060082/* 512MiB is large enough for testing purposes */
83static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070084
Jeff Sharkey36801cc2015-03-13 16:09:20 -070085static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080086static const unsigned int kMajorBlockExperimentalMin = 240;
87static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070088
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070089VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070090
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070091VolumeManager* VolumeManager::Instance() {
92 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070093 return sInstance;
94}
95
96VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080097 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060098 mNextObbId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -070099 // For security reasons, assume that a secure keyguard is
100 // showing until we hear otherwise
101 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700102}
103
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700104VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800105
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600106int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600107 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600108 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600109 if (access(kPathVirtualDisk, F_OK) != 0) {
110 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
111 }
112
113 if (mVirtualDisk == nullptr) {
114 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
115 LOG(ERROR) << "Failed to create virtual disk";
116 return -1;
117 }
118
119 struct stat buf;
120 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
121 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
122 return -1;
123 }
124
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700125 auto disk = new android::vold::Disk(
126 "virtual", buf.st_rdev, "virtual",
127 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600128 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700129 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600130 }
131 } else {
132 if (mVirtualDisk != nullptr) {
133 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700134 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600135
136 Loop::destroyByDevice(mVirtualDiskPath.c_str());
137 mVirtualDisk = nullptr;
138 }
139
140 if (access(kPathVirtualDisk, F_OK) == 0) {
141 unlink(kPathVirtualDisk);
142 }
143 }
144 return 0;
145}
146
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700147int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800148 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700149 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800150}
151
San Mehatf1b736b2009-10-10 17:22:08 -0700152int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600153 ATRACE_NAME("VolumeManager::start");
154
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700155 // Always start from a clean slate by unmounting everything in
156 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700157 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700158
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600159 Devmapper::destroyAll();
160 Loop::destroyAll();
161
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700162 // Assume that we always have an emulated volume on internal
163 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700164 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700165 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700166 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700167 mInternalEmulated->create();
168
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600169 // Consider creating a virtual disk
170 updateVirtualDisk();
171
San Mehatf1b736b2009-10-10 17:22:08 -0700172 return 0;
173}
174
175int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700176 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 mInternalEmulated->destroy();
178 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700179 return 0;
180}
181
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700182void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700183 std::lock_guard<std::mutex> lock(mLock);
184
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700185 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700186 LOG(DEBUG) << "----------------";
187 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700188 evt->dump();
189 }
San Mehatf1b736b2009-10-10 17:22:08 -0700190
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700191 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
192 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700193
194 if (devType != "disk") return;
195
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600196 int major = std::stoi(evt->findParam("MAJOR"));
197 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700198 dev_t device = makedev(major, minor);
199
200 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700201 case NetlinkEvent::Action::kAdd: {
202 for (const auto& source : mDiskSources) {
203 if (source->matches(eventPath)) {
204 // For now, assume that MMC and virtio-blk (the latter is
205 // emulator-specific; see Disk.cpp for details) devices are SD,
206 // and that everything else is USB
207 int flags = source->getFlags();
208 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
209 major >= (int)kMajorBlockExperimentalMin &&
210 major <= (int)kMajorBlockExperimentalMax)) {
211 flags |= android::vold::Disk::Flags::kSd;
212 } else {
213 flags |= android::vold::Disk::Flags::kUsb;
214 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700215
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700216 auto disk =
217 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
218 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
219 break;
220 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700221 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700222 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700223 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700224 case NetlinkEvent::Action::kChange: {
225 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
226 handleDiskChanged(device);
227 break;
228 }
229 case NetlinkEvent::Action::kRemove: {
230 handleDiskRemoved(device);
231 break;
232 }
233 default: {
234 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
235 break;
236 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700237 }
238}
239
Jeff Sharkey401b2602017-12-14 22:15:20 -0700240void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
241 // For security reasons, if secure keyguard is showing, wait
242 // until the user unlocks the device to actually touch it
243 if (mSecureKeyguardShowing) {
244 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700245 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700246 mPendingDisks.push_back(disk);
247 } else {
248 disk->create();
249 mDisks.push_back(disk);
250 }
251}
252
253void VolumeManager::handleDiskChanged(dev_t device) {
254 for (const auto& disk : mDisks) {
255 if (disk->getDevice() == device) {
256 disk->readMetadata();
257 disk->readPartitions();
258 }
259 }
260
261 // For security reasons, we ignore all pending disks, since
262 // we'll scan them once the device is unlocked
263}
264
265void VolumeManager::handleDiskRemoved(dev_t device) {
266 auto i = mDisks.begin();
267 while (i != mDisks.end()) {
268 if ((*i)->getDevice() == device) {
269 (*i)->destroy();
270 i = mDisks.erase(i);
271 } else {
272 ++i;
273 }
274 }
275 auto j = mPendingDisks.begin();
276 while (j != mPendingDisks.end()) {
277 if ((*j)->getDevice() == device) {
278 j = mPendingDisks.erase(j);
279 } else {
280 ++j;
281 }
282 }
283}
284
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700285void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800286 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700287 mDiskSources.push_back(diskSource);
288}
289
290std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
291 for (auto disk : mDisks) {
292 if (disk->getId() == id) {
293 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700294 }
295 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700296 return nullptr;
297}
San Mehatf1b736b2009-10-10 17:22:08 -0700298
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700299std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800300 // Vold could receive "mount" after "shutdown" command in the extreme case.
301 // If this happens, mInternalEmulated will equal nullptr and
302 // we need to deal with it in order to avoid null pointer crash.
303 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700304 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700305 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700306 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700307 auto vol = disk->findVolume(id);
308 if (vol != nullptr) {
309 return vol;
310 }
311 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600312 for (const auto& vol : mObbVolumes) {
313 if (vol->getId() == id) {
314 return vol;
315 }
316 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700317 return nullptr;
318}
319
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700320void VolumeManager::listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700321 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700322 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700323 disk->listVolumes(type, list);
324 }
325}
326
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600327int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700328 std::string normalizedGuid;
329 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
330 LOG(WARNING) << "Invalid GUID " << partGuid;
331 return -1;
332 }
333
Paul Crowleyc6433a22017-10-24 14:54:43 -0700334 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700335 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
336 if (unlink(keyPath.c_str()) != 0) {
337 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700338 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700339 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700340 if (e4crypt_is_native()) {
341 if (!e4crypt_destroy_volume_keys(fsUuid)) {
342 success = false;
343 }
344 }
345 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700346}
347
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700348int VolumeManager::linkPrimary(userid_t userId) {
349 std::string source(mPrimary->getPath());
350 if (mPrimary->isEmulated()) {
351 source = StringPrintf("%s/%d", source.c_str(), userId);
352 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
353 }
354
355 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
356 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
357 if (errno != ENOENT) {
358 PLOG(WARNING) << "Failed to unlink " << target;
359 }
360 }
361 LOG(DEBUG) << "Linking " << source << " to " << target;
362 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
363 PLOG(WARNING) << "Failed to link";
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700364 return -errno;
365 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700366 return 0;
367}
368
369int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
370 const std::string& mntTargetRoot,
371 const std::string& packageName, const char* dirName) {
372 std::string mntSourceDir =
373 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
374 std::string mntTargetDir =
375 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
376 if (umount2(mntTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL && errno != ENOENT) {
377 PLOG(ERROR) << "Failed to unmount " << mntTargetDir;
378 return -1;
379 }
380 if (TEMP_FAILURE_RETRY(mount(mntSourceDir.c_str(), mntTargetDir.c_str(), nullptr,
381 MS_BIND | MS_REC, nullptr)) == -1) {
382 PLOG(ERROR) << "Failed to mount " << mntSourceDir << " to " << mntTargetDir;
383 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700384 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700385 if (TEMP_FAILURE_RETRY(
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700386 mount(nullptr, mntTargetDir.c_str(), nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
387 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTargetDir;
388 return -1;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700389 }
390 return 0;
391}
392
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700393int VolumeManager::mountPkgSpecificDirsForRunningProcs(
394 userid_t userId, const std::vector<std::string>& packageNames,
395 const std::vector<std::string>& visibleVolLabels) {
396 // TODO: New processes could be started while traversing over the existing
397 // processes which would end up not having the necessary bind mounts. This
398 // issue needs to be fixed, may be by doing multiple passes here?
399 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
400 if (!dirp) {
401 PLOG(ERROR) << "Failed to opendir /proc";
402 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700403 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700404
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700405 std::string rootName;
406 // Figure out root namespace to compare against below
407 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
408 PLOG(ERROR) << "Failed to read root namespace";
409 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700410 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700411
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700412 struct stat fullWriteSb;
413 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &fullWriteSb)) == -1) {
414 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
415 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700416 }
417
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700418 std::unordered_set<appid_t> validAppIds;
419 for (auto& package : packageNames) {
420 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700421 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700422 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700423
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700424 struct dirent* de;
425 // Poke through all running PIDs look for apps running in userId
426 while ((de = readdir(dirp.get()))) {
427 pid_t pid;
428 if (de->d_type != DT_DIR) continue;
429 if (!android::base::ParseInt(de->d_name, &pid)) continue;
430
431 const unique_fd pidFd(
432 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
433 if (pidFd.get() < 0) {
434 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700435 continue;
436 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700437 struct stat sb;
438 if (fstat(pidFd.get(), &sb) != 0) {
439 PLOG(WARNING) << "Failed to stat " << de->d_name;
440 continue;
441 }
442 if (multiuser_get_user_id(sb.st_uid) != userId) {
443 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700444 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700445
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700446 // Matches so far, but refuse to touch if in root namespace
447 LOG(VERBOSE) << "Found matching PID " << de->d_name;
448 std::string pidName;
449 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
450 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
451 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700452 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700453 if (rootName == pidName) {
454 LOG(WARNING) << "Skipping due to root namespace";
455 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700456 }
457
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700458 // Only update the mount points of processes running with one of validAppIds.
459 // This should skip any isolated uids.
460 appid_t appId = multiuser_get_app_id(sb.st_uid);
461 if (validAppIds.find(appId) == validAppIds.end()) {
462 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700463 }
464
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700465 std::vector<std::string> packagesForUid;
466 for (auto& package : userPackages) {
467 if (mAppIds[package] == appId) {
468 packagesForUid.push_back(package);
469 }
470 }
471 if (packagesForUid.empty()) {
472 continue;
473 }
474 const std::string& sandboxId = mSandboxIds[appId];
475
476 // We purposefully leave the namespace open across the fork
477 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
478 if (nsFd.get() < 0) {
479 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
480 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700481 }
482
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700483 pid_t child;
484 if (!(child = fork())) {
485 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
486 PLOG(ERROR) << "Failed to setns for " << de->d_name;
487 _exit(1);
488 }
489
490 struct stat storageSb;
491 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
492 PLOG(ERROR) << "Failed to stat /storage";
493 _exit(1);
494 }
495
496 // Some packages have access to full external storage, identify processes belonging
497 // to those packages by comparing inode no.s of /mnt/runtime/write and /storage
498 if (storageSb.st_dev == fullWriteSb.st_dev && storageSb.st_ino == fullWriteSb.st_ino) {
499 _exit(0);
500 } else {
501 // Some packages don't have access to external storage and processes belonging to
502 // those packages don't have anything mounted at /storage. So, identify those
503 // processes by comparing inode no.s of /mnt/user/%d/package/%s
504 // and /storage
505 std::string pkgStorageSource;
506 for (auto& package : packagesForUid) {
507 std::string sandbox =
508 StringPrintf("/mnt/user/%d/package/%s", userId, package.c_str());
509 struct stat s;
510 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &s)) == -1) {
511 PLOG(ERROR) << "Failed to stat " << sandbox;
512 _exit(1);
513 }
514 if (storageSb.st_dev == s.st_dev && storageSb.st_ino == s.st_ino) {
515 pkgStorageSource = sandbox;
516 break;
517 }
518 }
519 if (pkgStorageSource.empty()) {
520 _exit(0);
521 }
522 }
523
524 for (auto& volumeLabel : visibleVolLabels) {
525 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
526 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
527 if (volumeLabel == "emulated") {
528 StringAppendF(&mntSource, "/%d", userId);
529 StringAppendF(&mntTarget, "/%d", userId);
530 }
531 for (auto& package : packagesForUid) {
532 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
533 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
534 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
535 }
536 }
537 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700538 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700539
540 if (child == -1) {
541 PLOG(ERROR) << "Failed to fork";
542 } else {
543 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700544 }
545 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700546 return 0;
547}
548
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700549int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
550 const std::vector<std::string>& visibleVolLabels) {
551 if (visibleVolLabels.empty()) {
552 return 0;
553 }
554 for (auto& volumeLabel : visibleVolLabels) {
555 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
556 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
557 if (isVolPrimaryEmulated) {
558 StringAppendF(&volumeRoot, "/%d", userId);
559 if (fs_prepare_dir(volumeRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
560 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeRoot;
561 return -errno;
562 }
563 }
564
565 std::string sandboxRoot =
566 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
567 if (sandboxRoot.empty()) {
568 return -errno;
569 }
570 std::string sharedSandboxRoot;
571 StringAppendF(&sharedSandboxRoot, "%s/shared", sandboxRoot.c_str());
572 // Create shared sandbox base dir for apps with sharedUserIds
573 if (fs_prepare_dir(sharedSandboxRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
574 PLOG(ERROR) << "fs_prepare_dir failed on " << sharedSandboxRoot;
575 return -errno;
576 }
577
578 if (!createPkgSpecificDirRoots(volumeRoot)) {
579 return -errno;
580 }
581
582 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
583 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
584 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
585 return -errno;
586 }
587 mntTargetRoot.append("/package");
588 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
589 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
590 return -errno;
591 }
592
593 for (auto& packageName : packageNames) {
594 const auto& it = mAppIds.find(packageName);
595 if (it == mAppIds.end()) {
596 PLOG(ERROR) << "appId is not available for " << packageName;
597 continue;
598 }
599 appid_t appId = it->second;
600 std::string sandboxId = mSandboxIds[appId];
601 uid_t uid = multiuser_get_uid(userId, appId);
602
603 // [1] Create /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>
604 // [2] Create /mnt/user/0/package/<packageName>/emulated/0
605 // Mount [1] at [2]
606 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
607 if (pkgSandboxSourceDir.empty()) {
608 return -errno;
609 }
610 std::string pkgSandboxTargetDir = prepareSandboxTarget(
611 packageName, uid, volumeLabel, mntTargetRoot, isVolPrimaryEmulated);
612 if (pkgSandboxTargetDir.empty()) {
613 return -errno;
614 }
615 if (umount2(pkgSandboxTargetDir.c_str(), MNT_DETACH) == -1 && errno != EINVAL &&
616 errno != ENOENT) {
617 PLOG(ERROR) << "Failed to unmount " << pkgSandboxTargetDir;
618 return -errno;
619 }
620 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
621 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
622 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
623 << pkgSandboxTargetDir;
624 return -errno;
625 }
626 if (TEMP_FAILURE_RETRY(mount(nullptr, pkgSandboxTargetDir.c_str(), nullptr,
627 MS_SLAVE | MS_REC, nullptr)) == -1) {
628 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
629 << pkgSandboxTargetDir;
630 return -errno;
631 }
632
633 // Create Android/{data,media,obb}/<packageName> segments at
634 // [1] /mnt/runtime/write/emulated/0/ and
635 // [2] /mnt/runtime/write/emulated/0/Android/sandbox/<sandboxId>/emulated/0/
636 if (!createPkgSpecificDirs(packageName, uid, volumeRoot, pkgSandboxSourceDir)) {
637 return -errno;
638 }
639
640 if (volumeLabel == mPrimary->getLabel()) {
641 // Create [1] /mnt/user/0/package/<packageName>/self/
642 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
643 // Mount [2] at [1]
644 std::string pkgPrimaryTargetDir =
645 StringPrintf("%s/%s/self", mntTargetRoot.c_str(), packageName.c_str());
646 if (fs_prepare_dir(pkgPrimaryTargetDir.c_str(), 0755, uid, uid) != 0) {
647 PLOG(ERROR) << "Failed to fs_prepare_dir on " << pkgPrimaryTargetDir;
648 return -errno;
649 }
650 StringAppendF(&pkgPrimaryTargetDir, "/primary");
651 std::string primarySource(mPrimary->getPath());
652 if (isVolPrimaryEmulated) {
653 StringAppendF(&primarySource, "/%d", userId);
654 }
655 if (TEMP_FAILURE_RETRY(unlink(pkgPrimaryTargetDir.c_str()))) {
656 if (errno != ENOENT) {
657 PLOG(ERROR) << "Failed to unlink " << pkgPrimaryTargetDir;
658 }
659 }
660 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), pkgPrimaryTargetDir.c_str()))) {
661 PLOG(ERROR) << "Failed to link " << primarySource << " at "
662 << pkgPrimaryTargetDir;
663 return -errno;
664 }
665 }
666 }
667 }
668 mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels);
669 return 0;
670}
671
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700672std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
673 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700674 std::string path(pathPrefix);
675 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
676 for (size_t i = 0; i < subDirList.size(); ++i) {
677 std::string subDir = subDirList[i];
678 if (subDir.empty()) {
679 continue;
680 }
681 StringAppendF(&path, "/%s", subDir.c_str());
682 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
683 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
684 return kEmptyString;
685 }
686 }
687 return path;
688}
689
690std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700691 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700692 std::string sandboxSourceDir(sandboxRootDir);
693 if (android::base::StartsWith(sandboxId, "shared:")) {
694 StringAppendF(&sandboxSourceDir, "/shared/%s", sandboxId.substr(7).c_str());
695 } else {
696 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
697 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700698 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
699 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
700 return kEmptyString;
701 }
702 return sandboxSourceDir;
703}
704
705std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700706 const std::string& volumeLabel,
707 const std::string& mntTargetRootDir,
708 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700709 std::string segment;
710 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700711 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
712 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700713 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700714 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700715 }
716 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
717}
718
719std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700720 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700721 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
722 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
723 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
724 return kEmptyString;
725 }
726 return dataSourceDir;
727}
728
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700729bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
730 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
731 if (fs_prepare_dir(volumeAndroidRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
732 PLOG(ERROR) << "fs_prepare_dir failed on " << volumeAndroidRoot;
733 return false;
734 }
735 std::array<std::string, 3> dirs = {"data", "media", "obb"};
736 for (auto& dir : dirs) {
737 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
738 if (fs_prepare_dir(path.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
739 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
740 return false;
741 }
742 }
743 return true;
744}
745
746bool VolumeManager::createPkgSpecificDirs(const std::string& packageName, uid_t uid,
747 const std::string& volumeRoot,
748 const std::string& sandboxDirRoot) {
749 std::array<std::string, 3> dirs = {"data", "media", "obb"};
750 for (auto& dir : dirs) {
751 std::string sourceDir = StringPrintf("%s/Android/%s", volumeRoot.c_str(), dir.c_str());
752 if (prepareSubDirs(sourceDir, packageName, 0755, uid, uid).empty()) {
753 return false;
754 }
755 std::string sandboxSegment =
756 StringPrintf("Android/%s/%s/", dir.c_str(), packageName.c_str());
757 if (prepareSubDirs(sandboxDirRoot, sandboxSegment, 0755, uid, uid).empty()) {
758 return false;
759 }
760 }
761 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700762}
763
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700764int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
765 mAddedUsers[userId] = userSerialNumber;
766 return 0;
767}
768
769int VolumeManager::onUserRemoved(userid_t userId) {
770 mAddedUsers.erase(userId);
771 return 0;
772}
773
Sudheer Shankaebaad1c2018-07-31 16:39:59 -0700774int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700775 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700776 // Note that sometimes the system will spin up processes from Zygote
777 // before actually starting the user, so we're okay if Zygote
778 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600779 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700780 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
781
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700782 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700783 mUserPackages[userId] = packageNames;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700784 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700785 linkPrimary(userId);
786 }
787 if (GetBoolProperty(kIsolatedStorage, false)) {
788 std::vector<std::string> visibleVolLabels;
789 for (auto& volId : mVisibleVolumeIds) {
790 auto vol = findVolume(volId);
791 userid_t mountUserId = vol->getMountUserId();
792 if (mountUserId == userId || vol->isEmulated()) {
793 visibleVolLabels.push_back(vol->getLabel());
794 }
795 }
796 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
797 return -errno;
798 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700799 }
800 return 0;
801}
802
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700803int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700804 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700805 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700806
807 std::string mntTargetDir = StringPrintf("/mnt/user/%d", userId);
808 if (android::vold::UnmountTree(mntTargetDir) != 0) {
809 PLOG(ERROR) << "unmountTree on " << mntTargetDir << " failed";
810 return -errno;
811 }
812 if (android::vold::DeleteDirContentsAndDir(mntTargetDir) < 0) {
813 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << mntTargetDir;
814 return -errno;
815 }
816 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << mntTargetDir;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700817 return 0;
818}
819
Sudheer Shankad484aa92018-07-31 10:07:34 -0700820int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700821 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700822 for (size_t i = 0; i < packageNames.size(); ++i) {
823 mAppIds[packageNames[i]] = appIds[i];
824 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700825 return 0;
826}
827
828int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700829 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700830 for (size_t i = 0; i < appIds.size(); ++i) {
831 mSandboxIds[appIds[i]] = sandboxIds[i];
832 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700833 return 0;
834}
835
Sudheer Shankac7562092018-08-24 10:20:56 -0700836int VolumeManager::mountExternalStorageForApp(const std::string& packageName, appid_t appId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700837 const std::string& sandboxId, userid_t userId) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700838 if (!GetBoolProperty(kIsolatedStorage, false)) {
839 return 0;
840 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
841 // User not started, no need to do anything now. Required bind mounts for the package will
842 // be created when the user starts.
843 return 0;
844 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700845 LOG(VERBOSE) << "mountExternalStorageForApp: " << packageName << ", appId=" << appId
846 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700847 mUserPackages[userId].push_back(packageName);
848 mAppIds[packageName] = appId;
849 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700850
851 std::vector<std::string> visibleVolLabels;
852 for (auto& volId : mVisibleVolumeIds) {
853 auto vol = findVolume(volId);
854 userid_t mountUserId = vol->getMountUserId();
855 if (mountUserId == userId || vol->isEmulated()) {
856 visibleVolLabels.push_back(vol->getLabel());
857 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700858 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700859 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700860}
861
Jeff Sharkey401b2602017-12-14 22:15:20 -0700862int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
863 mSecureKeyguardShowing = isShowing;
864 if (!mSecureKeyguardShowing) {
865 // Now that secure keyguard has been dismissed, process
866 // any pending disks
867 for (const auto& disk : mPendingDisks) {
868 disk->create();
869 mDisks.push_back(disk);
870 }
871 mPendingDisks.clear();
872 }
873 return 0;
874}
875
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700876int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
877 if (!GetBoolProperty(kIsolatedStorage, false)) {
878 return 0;
879 }
880
881 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
882 return 0;
883 }
884
885 mVisibleVolumeIds.insert(vol->getId());
886 userid_t mountUserId = vol->getMountUserId();
887 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
888 // We don't want to create another shared_ptr here because then we will end up with
889 // two shared_ptrs owning the underlying pointer without sharing it.
890 mPrimary = findVolume(vol->getId());
891 for (userid_t userId : mStartedUsers) {
892 if (linkPrimary(userId) != 0) {
893 return -errno;
894 }
895 }
896 }
897 if (vol->isEmulated()) {
898 for (userid_t userId : mStartedUsers) {
899 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
900 return -errno;
901 }
902 }
903 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
904 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
905 return -errno;
906 }
907 }
908 return 0;
909}
910
911int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
912 if (!GetBoolProperty(kIsolatedStorage, false)) {
913 return 0;
914 }
915
916 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
917 return 0;
918 }
919
920 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
921 mPrimary = nullptr;
922 }
923
924 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
925 userid_t mountUserId = vol->getMountUserId();
926 if (vol->isEmulated()) {
927 for (userid_t userId : mStartedUsers) {
928 if (destroySandboxesForVol(vol, userId) != 0) {
929 return -errno;
930 }
931 }
932 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
933 if (destroySandboxesForVol(vol, mountUserId) != 0) {
934 return -errno;
935 }
936 }
937 return 0;
938}
939
940int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
941 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
942 const std::vector<std::string>& packageNames = mUserPackages[userId];
943 for (auto& packageName : packageNames) {
944 std::string volSandboxRoot = StringPrintf("/mnt/user/%d/package/%s/%s", userId,
945 packageName.c_str(), vol->getLabel().c_str());
946 if (android::vold::UnmountTree(volSandboxRoot) != 0) {
947 PLOG(ERROR) << "unmountTree on " << volSandboxRoot << " failed";
948 continue;
949 }
950 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
951 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
952 continue;
953 }
954 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
955 }
956 return 0;
957}
958
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700959int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700960 if (GetBoolProperty(kIsolatedStorage, false)) {
961 return 0;
962 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700963 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700964 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700965 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700966 }
967 return 0;
968}
969
Jeff Sharkey3472e522017-10-06 18:02:53 -0600970static int unmount_tree(const std::string& prefix) {
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700971 return android::vold::UnmountTree(prefix);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700972}
973
Jeff Sharkey66270a22015-06-24 11:49:24 -0700974int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700975 // If the isolated storage is enabled, return -1 since in the isolated storage world, there
976 // are no longer any runtime storage permissions, so this shouldn't be called anymore.
977 if (GetBoolProperty(kIsolatedStorage, false)) {
978 return -1;
979 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700980 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
981
982 DIR* dir;
983 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600984 std::string rootName;
985 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700986 int pidFd;
987 int nsFd;
988 struct stat sb;
989 pid_t child;
990
991 if (!(dir = opendir("/proc"))) {
992 PLOG(ERROR) << "Failed to opendir";
993 return -1;
994 }
995
996 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600997 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
998 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700999 closedir(dir);
1000 return -1;
1001 }
1002
1003 // Poke through all running PIDs look for apps running as UID
1004 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001005 pid_t pid;
1006 if (de->d_type != DT_DIR) continue;
1007 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1008
Jeff Sharkey66270a22015-06-24 11:49:24 -07001009 pidFd = -1;
1010 nsFd = -1;
1011
1012 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1013 if (pidFd < 0) {
1014 goto next;
1015 }
1016 if (fstat(pidFd, &sb) != 0) {
1017 PLOG(WARNING) << "Failed to stat " << de->d_name;
1018 goto next;
1019 }
1020 if (sb.st_uid != uid) {
1021 goto next;
1022 }
1023
1024 // Matches so far, but refuse to touch if in root namespace
1025 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001026 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001027 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1028 goto next;
1029 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001030 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001031 LOG(WARNING) << "Skipping due to root namespace";
1032 goto next;
1033 }
1034
1035 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001036 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -07001037 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001038 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001039 goto next;
1040 }
1041
1042 if (!(child = fork())) {
1043 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001044 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001045 _exit(1);
1046 }
1047
Jeff Sharkey3472e522017-10-06 18:02:53 -06001048 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001049
1050 std::string storageSource;
1051 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001052 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001053 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001054 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001055 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001056 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001057 } else {
1058 // Sane default of no storage visible
1059 _exit(0);
1060 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001061 if (TEMP_FAILURE_RETRY(
1062 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1063 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001064 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001065 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001066 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1067 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001068 _exit(1);
1069 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001070
1071 // Mount user-specific symlink helper into place
1072 userid_t user_id = multiuser_get_user_id(uid);
1073 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001074 if (TEMP_FAILURE_RETRY(
1075 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1076 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001077 _exit(1);
1078 }
1079
Jeff Sharkey66270a22015-06-24 11:49:24 -07001080 _exit(0);
1081 }
1082
1083 if (child == -1) {
1084 PLOG(ERROR) << "Failed to fork";
1085 goto next;
1086 } else {
1087 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1088 }
1089
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001090 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001091 close(nsFd);
1092 close(pidFd);
1093 }
1094 closedir(dir);
1095 return 0;
1096}
1097
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001098int VolumeManager::reset() {
1099 // Tear down all existing disks/volumes and start from a blank slate so
1100 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001101 if (mInternalEmulated != nullptr) {
1102 mInternalEmulated->destroy();
1103 mInternalEmulated->create();
1104 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001105 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001106 disk->destroy();
1107 disk->create();
1108 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001109 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001110 mAddedUsers.clear();
1111 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001112
1113 mUserPackages.clear();
1114 mAppIds.clear();
1115 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001116 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001117
1118 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001119 android::vold::UnmountTree("/mnt/user/");
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001120 return 0;
1121}
1122
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001123// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001124int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001125 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001126 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001127 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001128 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001129 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001130 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001131 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001132 disk->destroy();
1133 }
1134 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001135 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001136 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001137 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001138}
1139
Jeff Sharkey9c484982015-03-31 10:35:33 -07001140int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001141 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001142 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001143
Jeff Sharkey9c484982015-03-31 10:35:33 -07001144 // First, try gracefully unmounting all known devices
1145 if (mInternalEmulated != nullptr) {
1146 mInternalEmulated->unmount();
1147 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001148 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001149 disk->unmountAll();
1150 }
1151
1152 // Worst case we might have some stale mounts lurking around, so
1153 // force unmount those just to be safe.
1154 FILE* fp = setmntent("/proc/mounts", "r");
1155 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001156 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001157 return -errno;
1158 }
1159
1160 // Some volumes can be stacked on each other, so force unmount in
1161 // reverse order to give us the best chance of success.
1162 std::list<std::string> toUnmount;
1163 mntent* mentry;
1164 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001165 auto test = std::string(mentry->mnt_dir);
Tri Vobca5cd72018-04-16 14:27:10 -07001166 if ((android::base::StartsWith(test, "/mnt/") &&
Bowgo Tsaic0cd37b2018-06-29 10:31:07 +08001167 !android::base::StartsWith(test, "/mnt/vendor") &&
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001168 !android::base::StartsWith(test, "/mnt/product")) ||
Tri Vobca5cd72018-04-16 14:27:10 -07001169 android::base::StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001170 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001171 }
1172 }
1173 endmntent(fp);
1174
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001175 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001176 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001177 android::vold::ForceUnmount(path);
1178 }
1179
1180 return 0;
1181}
1182
Jeff Sharkey3472e522017-10-06 18:02:53 -06001183int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001184 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -06001185 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001186 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001187 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001188 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001189 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001190 return -EINVAL;
1191 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001192}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001193
1194static size_t kAppFuseMaxMountPointName = 32;
1195
1196static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
1197 if (name.size() > kAppFuseMaxMountPointName) {
1198 LOG(ERROR) << "AppFuse mount name is too long.";
1199 return -EINVAL;
1200 }
1201 for (size_t i = 0; i < name.size(); i++) {
1202 if (!isalnum(name[i])) {
1203 LOG(ERROR) << "AppFuse mount name contains invalid character.";
1204 return -EINVAL;
1205 }
1206 }
1207 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
1208 return android::OK;
1209}
1210
1211static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
1212 // Remove existing mount.
1213 android::vold::ForceUnmount(path);
1214
1215 const auto opts = android::base::StringPrintf(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001216 "fd=%i,"
1217 "rootmode=40000,"
1218 "default_permissions,"
1219 "allow_other,"
1220 "user_id=%d,group_id=%d,"
1221 "context=\"u:object_r:app_fuse_file:s0\","
1222 "fscontext=u:object_r:app_fusefs:s0",
1223 device_fd, uid, uid);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001224
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001225 const int result =
1226 TEMP_FAILURE_RETRY(mount("/dev/fuse", path.c_str(), "fuse",
1227 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001228 if (result != 0) {
1229 PLOG(ERROR) << "Failed to mount " << path;
1230 return -errno;
1231 }
1232
1233 return android::OK;
1234}
1235
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001236static android::status_t runCommandInNamespace(const std::string& command, uid_t uid, pid_t pid,
1237 const std::string& path, int device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001238 if (DEBUG_APPFUSE) {
1239 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
1240 << " in namespace " << uid;
1241 }
1242
1243 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
1244 if (dir.get() == -1) {
1245 PLOG(ERROR) << "Failed to open /proc";
1246 return -errno;
1247 }
1248
1249 // Obtains process file descriptor.
1250 const std::string pid_str = android::base::StringPrintf("%d", pid);
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001251 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 -06001252 if (pid_fd.get() == -1) {
1253 PLOG(ERROR) << "Failed to open /proc/" << pid;
1254 return -errno;
1255 }
1256
1257 // Check UID of process.
1258 {
1259 struct stat sb;
1260 const int result = fstat(pid_fd.get(), &sb);
1261 if (result == -1) {
1262 PLOG(ERROR) << "Failed to stat /proc/" << pid;
1263 return -errno;
1264 }
1265 if (sb.st_uid != AID_SYSTEM) {
1266 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001267 << ", actual=" << sb.st_uid;
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001268 return -EPERM;
1269 }
1270 }
1271
1272 // Matches so far, but refuse to touch if in root namespace
1273 {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001274 std::string rootName;
1275 std::string pidName;
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001276 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName) ||
1277 !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001278 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001279 return -EPERM;
1280 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001281 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001282 LOG(ERROR) << "Don't mount appfuse in root namespace";
1283 return -EPERM;
1284 }
1285 }
1286
1287 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001288 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001289 if (ns_fd.get() < 0) {
1290 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
1291 return -errno;
1292 }
1293
1294 int child = fork();
1295 if (child == 0) {
1296 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
1297 PLOG(ERROR) << "Failed to setns";
1298 _exit(-errno);
1299 }
1300
1301 if (command == "mount") {
1302 _exit(mountInNamespace(uid, device_fd, path));
1303 } else if (command == "unmount") {
1304 // If it's just after all FD opened on mount point are closed, umount2 can fail with
1305 // EBUSY. To avoid the case, specify MNT_DETACH.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001306 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 && errno != EINVAL &&
1307 errno != ENOENT) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001308 PLOG(ERROR) << "Failed to unmount directory.";
1309 _exit(-errno);
1310 }
1311 if (rmdir(path.c_str()) != 0) {
1312 PLOG(ERROR) << "Failed to remove the mount directory.";
1313 _exit(-errno);
1314 }
1315 _exit(android::OK);
1316 } else {
1317 LOG(ERROR) << "Unknown appfuse command " << command;
1318 _exit(-EPERM);
1319 }
1320 }
1321
1322 if (child == -1) {
1323 PLOG(ERROR) << "Failed to folk child process";
1324 return -errno;
1325 }
1326
1327 android::status_t status;
1328 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
1329
1330 return status;
1331}
1332
1333int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001334 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001335 int id = mNextObbId++;
1336
1337 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001338 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001339 vol->create();
1340
1341 mObbVolumes.push_back(vol);
1342 *outVolId = vol->getId();
1343 return android::OK;
1344}
1345
1346int VolumeManager::destroyObb(const std::string& volId) {
1347 auto i = mObbVolumes.begin();
1348 while (i != mObbVolumes.end()) {
1349 if ((*i)->getId() == volId) {
1350 (*i)->destroy();
1351 i = mObbVolumes.erase(i);
1352 } else {
1353 ++i;
1354 }
1355 }
1356 return android::OK;
1357}
1358
1359int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001360 android::base::unique_fd* device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001361 std::string name = std::to_string(mountId);
1362
1363 // Check mount point name.
1364 std::string path;
1365 if (getMountPath(uid, name, &path) != android::OK) {
1366 LOG(ERROR) << "Invalid mount point name";
1367 return -1;
1368 }
1369
1370 // Create directories.
1371 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
1372 if (result != android::OK) {
1373 PLOG(ERROR) << "Failed to prepare directory " << path;
1374 return -1;
1375 }
1376
1377 // Open device FD.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001378 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001379 if (device_fd->get() == -1) {
1380 PLOG(ERROR) << "Failed to open /dev/fuse";
1381 return -1;
1382 }
1383
1384 // Mount.
1385 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
1386}
1387
1388int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
1389 std::string name = std::to_string(mountId);
1390
1391 // Check mount point name.
1392 std::string path;
1393 if (getMountPath(uid, name, &path) != android::OK) {
1394 LOG(ERROR) << "Invalid mount point name";
1395 return -1;
1396 }
1397
1398 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
1399}