blob: efbcf41d1fa065d4fcde222e15f592864cd12b32 [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>
San Mehata19b2502010-01-06 10:33:53 -080033
San Mehata2677e42009-12-13 10:40:18 -080034#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070035
Elliott Hughes7e128fb2015-12-04 15:50:53 -080036#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070037#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060038#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/strings.h>
41
Jeff Sharkey71ebe152013-09-17 17:24:38 -070042#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060043#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070044
Robert Craigb9e3ba52014-02-04 10:53:00 -050045#include <selinux/android.h>
46
San Mehatfd7f5872009-10-12 11:32:47 -070047#include <sysutils/NetlinkEvent.h>
48
Kenny Root344ca102012-04-03 17:23:01 -070049#include <private/android_filesystem_config.h>
50
Paul Crowleyc6433a22017-10-24 14:54:43 -070051#include <ext4_utils/ext4_crypt.h>
52
53#include "Devmapper.h"
54#include "Ext4Crypt.h"
San Mehata19b2502010-01-06 10:33:53 -080055#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070056#include "NetlinkManager.h"
57#include "Process.h"
58#include "Utils.h"
59#include "VoldUtil.h"
60#include "VolumeManager.h"
61#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070062#include "fs/Ext4.h"
63#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070064#include "model/EmulatedVolume.h"
65#include "model/ObbVolume.h"
San Mehat23969932010-01-09 07:08:06 -080066
Sudheer Shanka53947a32018-08-01 10:24:13 -070067using android::base::GetBoolProperty;
68using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070069using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060070using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070071
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060072static const char* kPathUserMount = "/mnt/user";
73static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
74
Sudheer Shanka53947a32018-08-01 10:24:13 -070075static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060076static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
77
Sudheer Shanka53947a32018-08-01 10:24:13 -070078static const std::string kEmptyString("");
79
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060080/* 512MiB is large enough for testing purposes */
81static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070082
Jeff Sharkey36801cc2015-03-13 16:09:20 -070083static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080084static const unsigned int kMajorBlockExperimentalMin = 240;
85static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070086
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070087VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070088
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070089VolumeManager* VolumeManager::Instance() {
90 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070091 return sInstance;
92}
93
94VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080095 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060096 mNextObbId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -070097 // For security reasons, assume that a secure keyguard is
98 // showing until we hear otherwise
99 mSecureKeyguardShowing = true;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700100 mMntStorageCreated = false;
San Mehatf1b736b2009-10-10 17:22:08 -0700101}
102
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700103VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800104
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600105int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600106 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600107 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600108 if (access(kPathVirtualDisk, F_OK) != 0) {
109 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
110 }
111
112 if (mVirtualDisk == nullptr) {
113 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
114 LOG(ERROR) << "Failed to create virtual disk";
115 return -1;
116 }
117
118 struct stat buf;
119 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
120 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
121 return -1;
122 }
123
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700124 auto disk = new android::vold::Disk(
125 "virtual", buf.st_rdev, "virtual",
126 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600127 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700128 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129 }
130 } else {
131 if (mVirtualDisk != nullptr) {
132 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700133 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600134
135 Loop::destroyByDevice(mVirtualDiskPath.c_str());
136 mVirtualDisk = nullptr;
137 }
138
139 if (access(kPathVirtualDisk, F_OK) == 0) {
140 unlink(kPathVirtualDisk);
141 }
142 }
143 return 0;
144}
145
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700146int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800147 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700148 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800149}
150
San Mehatf1b736b2009-10-10 17:22:08 -0700151int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600152 ATRACE_NAME("VolumeManager::start");
153
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700154 // Always start from a clean slate by unmounting everything in
155 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700156 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700157
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600158 Devmapper::destroyAll();
159 Loop::destroyAll();
160
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700161 // Assume that we always have an emulated volume on internal
162 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700163 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700164 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700165 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700166 mInternalEmulated->create();
167
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600168 // Consider creating a virtual disk
169 updateVirtualDisk();
170
San Mehatf1b736b2009-10-10 17:22:08 -0700171 return 0;
172}
173
174int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700175 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700176 mInternalEmulated->destroy();
177 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700178 return 0;
179}
180
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700181void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700182 std::lock_guard<std::mutex> lock(mLock);
183
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700184 if (mDebug) {
185 LOG(VERBOSE) << "----------------";
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700186 LOG(VERBOSE) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700187 evt->dump();
188 }
San Mehatf1b736b2009-10-10 17:22:08 -0700189
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700190 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
191 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192
193 if (devType != "disk") return;
194
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600195 int major = std::stoi(evt->findParam("MAJOR"));
196 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700197 dev_t device = makedev(major, minor);
198
199 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700200 case NetlinkEvent::Action::kAdd: {
201 for (const auto& source : mDiskSources) {
202 if (source->matches(eventPath)) {
203 // For now, assume that MMC and virtio-blk (the latter is
204 // emulator-specific; see Disk.cpp for details) devices are SD,
205 // and that everything else is USB
206 int flags = source->getFlags();
207 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
208 major >= (int)kMajorBlockExperimentalMin &&
209 major <= (int)kMajorBlockExperimentalMax)) {
210 flags |= android::vold::Disk::Flags::kSd;
211 } else {
212 flags |= android::vold::Disk::Flags::kUsb;
213 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700214
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700215 auto disk =
216 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
217 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
218 break;
219 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700220 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700221 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700222 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700223 case NetlinkEvent::Action::kChange: {
224 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
225 handleDiskChanged(device);
226 break;
227 }
228 case NetlinkEvent::Action::kRemove: {
229 handleDiskRemoved(device);
230 break;
231 }
232 default: {
233 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
234 break;
235 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700236 }
237}
238
Jeff Sharkey401b2602017-12-14 22:15:20 -0700239void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
240 // For security reasons, if secure keyguard is showing, wait
241 // until the user unlocks the device to actually touch it
242 if (mSecureKeyguardShowing) {
243 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700244 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700245 mPendingDisks.push_back(disk);
246 } else {
247 disk->create();
248 mDisks.push_back(disk);
249 }
250}
251
252void VolumeManager::handleDiskChanged(dev_t device) {
253 for (const auto& disk : mDisks) {
254 if (disk->getDevice() == device) {
255 disk->readMetadata();
256 disk->readPartitions();
257 }
258 }
259
260 // For security reasons, we ignore all pending disks, since
261 // we'll scan them once the device is unlocked
262}
263
264void VolumeManager::handleDiskRemoved(dev_t device) {
265 auto i = mDisks.begin();
266 while (i != mDisks.end()) {
267 if ((*i)->getDevice() == device) {
268 (*i)->destroy();
269 i = mDisks.erase(i);
270 } else {
271 ++i;
272 }
273 }
274 auto j = mPendingDisks.begin();
275 while (j != mPendingDisks.end()) {
276 if ((*j)->getDevice() == device) {
277 j = mPendingDisks.erase(j);
278 } else {
279 ++j;
280 }
281 }
282}
283
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700284void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800285 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700286 mDiskSources.push_back(diskSource);
287}
288
289std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
290 for (auto disk : mDisks) {
291 if (disk->getId() == id) {
292 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700293 }
294 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700295 return nullptr;
296}
San Mehatf1b736b2009-10-10 17:22:08 -0700297
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700298std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800299 // Vold could receive "mount" after "shutdown" command in the extreme case.
300 // If this happens, mInternalEmulated will equal nullptr and
301 // we need to deal with it in order to avoid null pointer crash.
302 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700303 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700304 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700305 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700306 auto vol = disk->findVolume(id);
307 if (vol != nullptr) {
308 return vol;
309 }
310 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600311 for (const auto& vol : mObbVolumes) {
312 if (vol->getId() == id) {
313 return vol;
314 }
315 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700316 return nullptr;
317}
318
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700319void VolumeManager::listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700320 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700321 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700322 disk->listVolumes(type, list);
323 }
324}
325
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600326int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700327 std::string normalizedGuid;
328 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
329 LOG(WARNING) << "Invalid GUID " << partGuid;
330 return -1;
331 }
332
Paul Crowleyc6433a22017-10-24 14:54:43 -0700333 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700334 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
335 if (unlink(keyPath.c_str()) != 0) {
336 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700337 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700338 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700339 if (e4crypt_is_native()) {
340 if (!e4crypt_destroy_volume_keys(fsUuid)) {
341 success = false;
342 }
343 }
344 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700345}
346
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700347static int prepareMntStorageDir() {
348 std::string mntTarget("/mnt/storage");
349 if (fs_prepare_dir(mntTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
350 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTarget;
351 return -errno;
352 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700353 if (TEMP_FAILURE_RETRY(mount("/mnt/runtime/write", mntTarget.c_str(), nullptr, MS_BIND | MS_REC,
354 nullptr)) == -1) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700355 PLOG(ERROR) << "Failed to mount /mnt/runtime/write at " << mntTarget;
356 return -errno;
357 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700358 if (TEMP_FAILURE_RETRY(
359 mount(nullptr, mntTarget.c_str(), nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700360 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTarget;
361 return -errno;
362 }
363 return 0;
364}
365
Sudheer Shanka53947a32018-08-01 10:24:13 -0700366int VolumeManager::linkPrimary(userid_t userId, const std::vector<std::string>& packageNames) {
367 if (GetBoolProperty(kIsolatedStorage, false)) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700368 // This should ideally go into start() but it's possible that system properties are not
369 // loaded at that point.
370 if (!mMntStorageCreated) {
371 prepareMntStorageDir();
372 mMntStorageCreated = true;
373 }
374
Sudheer Shankac7562092018-08-24 10:20:56 -0700375 if (mountSandboxesForPrimaryVol(userId, packageNames) != 0) {
Sudheer Shankaa695f252018-08-03 18:07:52 -0700376 return -errno;
377 }
378 // Keep /sdcard working for shell process
379 std::string primarySource(mPrimary->getPath());
Sudheer Shankac7562092018-08-24 10:20:56 -0700380 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
Sudheer Shankaa695f252018-08-03 18:07:52 -0700381 StringAppendF(&primarySource, "/%d", userId);
382 }
383 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
384 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
385 if (errno != ENOENT) {
386 PLOG(WARNING) << "Failed to unlink " << target;
387 }
388 }
389 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), target.c_str()))) {
390 PLOG(WARNING) << "Failed to link " << primarySource << " at " << target;
391 return -errno;
392 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700393 } else {
394 std::string source(mPrimary->getPath());
395 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
396 source = StringPrintf("%s/%d", source.c_str(), userId);
397 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
398 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700399
Sudheer Shanka53947a32018-08-01 10:24:13 -0700400 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
401 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
402 if (errno != ENOENT) {
403 PLOG(WARNING) << "Failed to unlink " << target;
404 }
405 }
406 LOG(DEBUG) << "Linking " << source << " to " << target;
407 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
408 PLOG(WARNING) << "Failed to link";
409 return -errno;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700410 }
411 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700412 return 0;
413}
414
Sudheer Shankac7562092018-08-24 10:20:56 -0700415int VolumeManager::mountSandboxesForPrimaryVol(userid_t userId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700416 const std::vector<std::string>& packageNames) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700417 std::string primaryRoot(StringPrintf("/mnt/storage/%s", mPrimary->getLabel().c_str()));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700418 bool isPrimaryEmulated = (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated);
Sudheer Shankac7562092018-08-24 10:20:56 -0700419 if (isPrimaryEmulated) {
420 StringAppendF(&primaryRoot, "/%d", userId);
421 if (fs_prepare_dir(primaryRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
422 PLOG(ERROR) << "fs_prepare_dir failed on " << primaryRoot;
423 return -errno;
424 }
425 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700426
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700427 std::string sandboxRoot =
428 prepareSubDirs(primaryRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700429 if (sandboxRoot.empty()) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700430 return -errno;
431 }
Sudheer Shankaf768c272018-08-04 10:10:27 -0700432 std::string sharedSandboxRoot;
433 StringAppendF(&sharedSandboxRoot, "%s/shared", sandboxRoot.c_str());
434 // Create shared sandbox base dir for apps with sharedUserIds
435 if (fs_prepare_dir(sharedSandboxRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
436 PLOG(ERROR) << "fs_prepare_dir failed on " << sharedSandboxRoot;
437 return -errno;
438 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700439
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700440 std::string dataRoot = prepareSubDirs(primaryRoot, "Android/data/", 0700, AID_ROOT, AID_ROOT);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700441 if (dataRoot.empty()) {
442 return -errno;
443 }
444
Sudheer Shankaa695f252018-08-03 18:07:52 -0700445 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
446 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
447 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
448 return -errno;
449 }
450 mntTargetRoot.append("/package");
451 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
452 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700453 return -errno;
454 }
455
456 for (auto& packageName : packageNames) {
457 const auto& it = mAppIds.find(packageName);
458 if (it == mAppIds.end()) {
459 PLOG(ERROR) << "appId is not available for " << packageName;
460 continue;
461 }
462 appid_t appId = it->second;
463 std::string sandboxId = mSandboxIds[appId];
464 uid_t uid = multiuser_get_uid(userId, appId);
465
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700466 // Create /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
Sudheer Shanka53947a32018-08-01 10:24:13 -0700467 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
468 if (pkgSandboxSourceDir.empty()) {
469 return -errno;
470 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700471
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700472 // Create [1] /mnt/storage/emulated/0/Android/data/<packageName>
473 // Create [2] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>/Android/data/<packageName>
Sudheer Shanka53947a32018-08-01 10:24:13 -0700474 // Mount [1] at [2]
475 std::string pkgDataSourceDir = preparePkgDataSource(packageName, uid, dataRoot);
476 if (pkgDataSourceDir.empty()) {
477 return -errno;
478 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700479 std::string pkgDataTargetDir = preparePkgDataTarget(packageName, uid, pkgSandboxSourceDir);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700480 if (pkgDataTargetDir.empty()) {
481 return -errno;
482 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700483 if (TEMP_FAILURE_RETRY(mount(pkgDataSourceDir.c_str(), pkgDataTargetDir.c_str(), nullptr,
484 MS_BIND | MS_REC, nullptr)) == -1) {
485 PLOG(ERROR) << "Failed to mount " << pkgDataSourceDir << " at " << pkgDataTargetDir;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700486 return -errno;
487 }
488
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700489 // Already created [1] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
490 // Create [2] /mnt/user/0/package/<packageName>/emulated/0
491 // Mount [1] at [2]
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700492 std::string pkgSandboxTargetDir = prepareSandboxTarget(
493 packageName, uid, mPrimary->getLabel(), mntTargetRoot, isPrimaryEmulated);
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700494 if (pkgSandboxTargetDir.empty()) {
495 return -errno;
496 }
497
498 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700499 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700500 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
501 << pkgSandboxTargetDir;
502 return -errno;
503 }
504
Sudheer Shanka53947a32018-08-01 10:24:13 -0700505 // Create [1] /mnt/user/0/package/<packageName>/self/primary
506 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
507 // Mount [2] at [1]
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700508 std::string pkgPrimaryTargetDir =
509 prepareSubDirs(StringPrintf("%s/%s", mntTargetRoot.c_str(), packageName.c_str()),
510 "self/primary/", 0755, uid, uid);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700511 if (pkgPrimaryTargetDir.empty()) {
512 return -errno;
513 }
514 if (TEMP_FAILURE_RETRY(mount(pkgSandboxTargetDir.c_str(), pkgPrimaryTargetDir.c_str(),
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700515 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700516 PLOG(ERROR) << "Failed to mount " << pkgSandboxTargetDir << " at "
517 << pkgPrimaryTargetDir;
518 return -errno;
519 }
520 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700521 return 0;
522}
523
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700524std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
525 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700526 std::string path(pathPrefix);
527 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
528 for (size_t i = 0; i < subDirList.size(); ++i) {
529 std::string subDir = subDirList[i];
530 if (subDir.empty()) {
531 continue;
532 }
533 StringAppendF(&path, "/%s", subDir.c_str());
534 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
535 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
536 return kEmptyString;
537 }
538 }
539 return path;
540}
541
542std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700543 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700544 std::string sandboxSourceDir(sandboxRootDir);
545 if (android::base::StartsWith(sandboxId, "shared:")) {
546 StringAppendF(&sandboxSourceDir, "/shared/%s", sandboxId.substr(7).c_str());
547 } else {
548 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
549 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700550 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
551 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
552 return kEmptyString;
553 }
554 return sandboxSourceDir;
555}
556
557std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700558 const std::string& volumeLabel,
559 const std::string& mntTargetRootDir,
560 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700561 std::string segment;
562 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700563 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
564 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700565 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700566 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700567 }
568 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
569}
570
571std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700572 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700573 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
574 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
575 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
576 return kEmptyString;
577 }
578 return dataSourceDir;
579}
580
581std::string VolumeManager::preparePkgDataTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700582 const std::string& pkgSandboxDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700583 std::string segment = StringPrintf("Android/data/%s/", packageName.c_str());
584 return prepareSubDirs(pkgSandboxDir, segment.c_str(), 0755, uid, uid);
585}
586
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700587int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
588 mAddedUsers[userId] = userSerialNumber;
589 return 0;
590}
591
592int VolumeManager::onUserRemoved(userid_t userId) {
593 mAddedUsers.erase(userId);
594 return 0;
595}
596
Sudheer Shankaebaad1c2018-07-31 16:39:59 -0700597int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700598 // Note that sometimes the system will spin up processes from Zygote
599 // before actually starting the user, so we're okay if Zygote
600 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600601 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700602 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
603
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700604 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700605 mUserPackages[userId] = packageNames;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700606 if (mPrimary) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700607 linkPrimary(userId, packageNames);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700608 }
609 return 0;
610}
611
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700612int VolumeManager::onUserStopped(userid_t userId) {
613 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700614 return 0;
615}
616
Sudheer Shankad484aa92018-07-31 10:07:34 -0700617int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700618 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700619 for (size_t i = 0; i < packageNames.size(); ++i) {
620 mAppIds[packageNames[i]] = appIds[i];
621 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700622 return 0;
623}
624
625int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700626 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700627 for (size_t i = 0; i < appIds.size(); ++i) {
628 mSandboxIds[appIds[i]] = sandboxIds[i];
629 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700630 return 0;
631}
632
Sudheer Shankac7562092018-08-24 10:20:56 -0700633int VolumeManager::mountExternalStorageForApp(const std::string& packageName, appid_t appId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700634 const std::string& sandboxId, userid_t userId) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700635 if (!GetBoolProperty(kIsolatedStorage, false)) {
636 return 0;
637 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
638 // User not started, no need to do anything now. Required bind mounts for the package will
639 // be created when the user starts.
640 return 0;
641 }
642 mUserPackages[userId].push_back(packageName);
643 mAppIds[packageName] = appId;
644 mSandboxIds[appId] = sandboxId;
645 if (mPrimary) {
646 return mountSandboxesForPrimaryVol(userId, {packageName});
647 }
648 return 0;
649}
650
Jeff Sharkey401b2602017-12-14 22:15:20 -0700651int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
652 mSecureKeyguardShowing = isShowing;
653 if (!mSecureKeyguardShowing) {
654 // Now that secure keyguard has been dismissed, process
655 // any pending disks
656 for (const auto& disk : mPendingDisks) {
657 disk->create();
658 mDisks.push_back(disk);
659 }
660 mPendingDisks.clear();
661 }
662 return 0;
663}
664
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700665int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
666 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700667 for (userid_t userId : mStartedUsers) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700668 linkPrimary(userId, mUserPackages[userId]);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700669 }
670 return 0;
671}
672
Jeff Sharkey3472e522017-10-06 18:02:53 -0600673static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700674 FILE* fp = setmntent("/proc/mounts", "r");
675 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600676 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700677 return -errno;
678 }
679
680 // Some volumes can be stacked on each other, so force unmount in
681 // reverse order to give us the best chance of success.
682 std::list<std::string> toUnmount;
683 mntent* mentry;
684 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600685 auto test = std::string(mentry->mnt_dir) + "/";
Elliott Hughes32a5b9a2017-12-20 12:38:47 -0800686 if (android::base::StartsWith(test, prefix)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600687 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700688 }
689 }
690 endmntent(fp);
691
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700692 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700693 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600694 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700695 }
696 }
697 return 0;
698}
699
Jeff Sharkey66270a22015-06-24 11:49:24 -0700700int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700701 // If the isolated storage is enabled, return -1 since in the isolated storage world, there
702 // are no longer any runtime storage permissions, so this shouldn't be called anymore.
703 if (GetBoolProperty(kIsolatedStorage, false)) {
704 return -1;
705 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700706 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
707
708 DIR* dir;
709 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600710 std::string rootName;
711 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700712 int pidFd;
713 int nsFd;
714 struct stat sb;
715 pid_t child;
716
717 if (!(dir = opendir("/proc"))) {
718 PLOG(ERROR) << "Failed to opendir";
719 return -1;
720 }
721
722 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600723 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
724 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700725 closedir(dir);
726 return -1;
727 }
728
729 // Poke through all running PIDs look for apps running as UID
730 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700731 pid_t pid;
732 if (de->d_type != DT_DIR) continue;
733 if (!android::base::ParseInt(de->d_name, &pid)) continue;
734
Jeff Sharkey66270a22015-06-24 11:49:24 -0700735 pidFd = -1;
736 nsFd = -1;
737
738 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
739 if (pidFd < 0) {
740 goto next;
741 }
742 if (fstat(pidFd, &sb) != 0) {
743 PLOG(WARNING) << "Failed to stat " << de->d_name;
744 goto next;
745 }
746 if (sb.st_uid != uid) {
747 goto next;
748 }
749
750 // Matches so far, but refuse to touch if in root namespace
751 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600752 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700753 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
754 goto next;
755 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600756 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700757 LOG(WARNING) << "Skipping due to root namespace";
758 goto next;
759 }
760
761 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700762 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700763 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700764 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700765 goto next;
766 }
767
768 if (!(child = fork())) {
769 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700770 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700771 _exit(1);
772 }
773
Jeff Sharkey3472e522017-10-06 18:02:53 -0600774 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700775
776 std::string storageSource;
777 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700778 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700779 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700780 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700781 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700782 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700783 } else {
784 // Sane default of no storage visible
785 _exit(0);
786 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700787 if (TEMP_FAILURE_RETRY(
788 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
789 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700790 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700791 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700792 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
793 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +0900794 _exit(1);
795 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700796
797 // Mount user-specific symlink helper into place
798 userid_t user_id = multiuser_get_user_id(uid);
799 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700800 if (TEMP_FAILURE_RETRY(
801 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
802 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700803 _exit(1);
804 }
805
Jeff Sharkey66270a22015-06-24 11:49:24 -0700806 _exit(0);
807 }
808
809 if (child == -1) {
810 PLOG(ERROR) << "Failed to fork";
811 goto next;
812 } else {
813 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
814 }
815
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700816 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700817 close(nsFd);
818 close(pidFd);
819 }
820 closedir(dir);
821 return 0;
822}
823
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700824int VolumeManager::reset() {
825 // Tear down all existing disks/volumes and start from a blank slate so
826 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800827 if (mInternalEmulated != nullptr) {
828 mInternalEmulated->destroy();
829 mInternalEmulated->create();
830 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700831 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700832 disk->destroy();
833 disk->create();
834 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600835 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700836 mAddedUsers.clear();
837 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700838
839 mUserPackages.clear();
840 mAppIds.clear();
841 mSandboxIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700842
843 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
844 unmount_tree("/mnt/user/");
845 // For unmounting dirs under /mnt/storage including the bind mount at /mnt/storage, that's
846 // why no trailing '/'
847 unmount_tree("/mnt/storage");
848 mMntStorageCreated = false;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700849 return 0;
850}
851
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700852// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700853int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700854 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700855 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700856 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700857 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700858 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700859 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700860 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700861 disk->destroy();
862 }
863 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700864 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700865 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700866 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700867}
868
Jeff Sharkey9c484982015-03-31 10:35:33 -0700869int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700870 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600871 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700872
Jeff Sharkey9c484982015-03-31 10:35:33 -0700873 // First, try gracefully unmounting all known devices
874 if (mInternalEmulated != nullptr) {
875 mInternalEmulated->unmount();
876 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700877 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700878 disk->unmountAll();
879 }
880
881 // Worst case we might have some stale mounts lurking around, so
882 // force unmount those just to be safe.
883 FILE* fp = setmntent("/proc/mounts", "r");
884 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600885 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700886 return -errno;
887 }
888
889 // Some volumes can be stacked on each other, so force unmount in
890 // reverse order to give us the best chance of success.
891 std::list<std::string> toUnmount;
892 mntent* mentry;
893 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600894 auto test = std::string(mentry->mnt_dir);
Tri Vobca5cd72018-04-16 14:27:10 -0700895 if ((android::base::StartsWith(test, "/mnt/") &&
Bowgo Tsaic0cd37b2018-06-29 10:31:07 +0800896 !android::base::StartsWith(test, "/mnt/vendor") &&
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700897 !android::base::StartsWith(test, "/mnt/product") &&
898 !android::base::StartsWith(test, "/mnt/storage")) ||
Tri Vobca5cd72018-04-16 14:27:10 -0700899 android::base::StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600900 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700901 }
902 }
903 endmntent(fp);
904
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700905 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600906 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700907 android::vold::ForceUnmount(path);
908 }
909
910 return 0;
911}
912
Jeff Sharkey3472e522017-10-06 18:02:53 -0600913int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700914 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600915 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700916 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600917 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700918 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600919 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700920 return -EINVAL;
921 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700922}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600923
924static size_t kAppFuseMaxMountPointName = 32;
925
926static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
927 if (name.size() > kAppFuseMaxMountPointName) {
928 LOG(ERROR) << "AppFuse mount name is too long.";
929 return -EINVAL;
930 }
931 for (size_t i = 0; i < name.size(); i++) {
932 if (!isalnum(name[i])) {
933 LOG(ERROR) << "AppFuse mount name contains invalid character.";
934 return -EINVAL;
935 }
936 }
937 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
938 return android::OK;
939}
940
941static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
942 // Remove existing mount.
943 android::vold::ForceUnmount(path);
944
945 const auto opts = android::base::StringPrintf(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700946 "fd=%i,"
947 "rootmode=40000,"
948 "default_permissions,"
949 "allow_other,"
950 "user_id=%d,group_id=%d,"
951 "context=\"u:object_r:app_fuse_file:s0\","
952 "fscontext=u:object_r:app_fusefs:s0",
953 device_fd, uid, uid);
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600954
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700955 const int result =
956 TEMP_FAILURE_RETRY(mount("/dev/fuse", path.c_str(), "fuse",
957 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600958 if (result != 0) {
959 PLOG(ERROR) << "Failed to mount " << path;
960 return -errno;
961 }
962
963 return android::OK;
964}
965
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700966static android::status_t runCommandInNamespace(const std::string& command, uid_t uid, pid_t pid,
967 const std::string& path, int device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600968 if (DEBUG_APPFUSE) {
969 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
970 << " in namespace " << uid;
971 }
972
973 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
974 if (dir.get() == -1) {
975 PLOG(ERROR) << "Failed to open /proc";
976 return -errno;
977 }
978
979 // Obtains process file descriptor.
980 const std::string pid_str = android::base::StringPrintf("%d", pid);
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700981 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 -0600982 if (pid_fd.get() == -1) {
983 PLOG(ERROR) << "Failed to open /proc/" << pid;
984 return -errno;
985 }
986
987 // Check UID of process.
988 {
989 struct stat sb;
990 const int result = fstat(pid_fd.get(), &sb);
991 if (result == -1) {
992 PLOG(ERROR) << "Failed to stat /proc/" << pid;
993 return -errno;
994 }
995 if (sb.st_uid != AID_SYSTEM) {
996 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700997 << ", actual=" << sb.st_uid;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600998 return -EPERM;
999 }
1000 }
1001
1002 // Matches so far, but refuse to touch if in root namespace
1003 {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001004 std::string rootName;
1005 std::string pidName;
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001006 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName) ||
1007 !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001008 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001009 return -EPERM;
1010 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001011 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001012 LOG(ERROR) << "Don't mount appfuse in root namespace";
1013 return -EPERM;
1014 }
1015 }
1016
1017 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001018 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001019 if (ns_fd.get() < 0) {
1020 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
1021 return -errno;
1022 }
1023
1024 int child = fork();
1025 if (child == 0) {
1026 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
1027 PLOG(ERROR) << "Failed to setns";
1028 _exit(-errno);
1029 }
1030
1031 if (command == "mount") {
1032 _exit(mountInNamespace(uid, device_fd, path));
1033 } else if (command == "unmount") {
1034 // If it's just after all FD opened on mount point are closed, umount2 can fail with
1035 // EBUSY. To avoid the case, specify MNT_DETACH.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001036 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 && errno != EINVAL &&
1037 errno != ENOENT) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001038 PLOG(ERROR) << "Failed to unmount directory.";
1039 _exit(-errno);
1040 }
1041 if (rmdir(path.c_str()) != 0) {
1042 PLOG(ERROR) << "Failed to remove the mount directory.";
1043 _exit(-errno);
1044 }
1045 _exit(android::OK);
1046 } else {
1047 LOG(ERROR) << "Unknown appfuse command " << command;
1048 _exit(-EPERM);
1049 }
1050 }
1051
1052 if (child == -1) {
1053 PLOG(ERROR) << "Failed to folk child process";
1054 return -errno;
1055 }
1056
1057 android::status_t status;
1058 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
1059
1060 return status;
1061}
1062
1063int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001064 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001065 int id = mNextObbId++;
1066
1067 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001068 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001069 vol->create();
1070
1071 mObbVolumes.push_back(vol);
1072 *outVolId = vol->getId();
1073 return android::OK;
1074}
1075
1076int VolumeManager::destroyObb(const std::string& volId) {
1077 auto i = mObbVolumes.begin();
1078 while (i != mObbVolumes.end()) {
1079 if ((*i)->getId() == volId) {
1080 (*i)->destroy();
1081 i = mObbVolumes.erase(i);
1082 } else {
1083 ++i;
1084 }
1085 }
1086 return android::OK;
1087}
1088
1089int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001090 android::base::unique_fd* device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001091 std::string name = std::to_string(mountId);
1092
1093 // Check mount point name.
1094 std::string path;
1095 if (getMountPath(uid, name, &path) != android::OK) {
1096 LOG(ERROR) << "Invalid mount point name";
1097 return -1;
1098 }
1099
1100 // Create directories.
1101 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
1102 if (result != android::OK) {
1103 PLOG(ERROR) << "Failed to prepare directory " << path;
1104 return -1;
1105 }
1106
1107 // Open device FD.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001108 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001109 if (device_fd->get() == -1) {
1110 PLOG(ERROR) << "Failed to open /dev/fuse";
1111 return -1;
1112 }
1113
1114 // Mount.
1115 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
1116}
1117
1118int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
1119 std::string name = std::to_string(mountId);
1120
1121 // Check mount point name.
1122 std::string path;
1123 if (getMountPath(uid, name, &path) != android::OK) {
1124 LOG(ERROR) << "Invalid mount point name";
1125 return -1;
1126 }
1127
1128 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
1129}