blob: 049adc847f4e316b41e49472e90aaaeeaadaf11d [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080022#include <mntent.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080028#include <sys/stat.h>
29#include <sys/types.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070030#include <sys/sysmacros.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
San Mehata19b2502010-01-06 10:33:53 -080033
San Mehata2677e42009-12-13 10:40:18 -080034#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070035
Elliott Hughes7e128fb2015-12-04 15:50:53 -080036#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070037#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060038#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/strings.h>
41
Jeff Sharkey71ebe152013-09-17 17:24:38 -070042#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060043#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070044
Robert Craigb9e3ba52014-02-04 10:53:00 -050045#include <selinux/android.h>
46
San Mehatfd7f5872009-10-12 11:32:47 -070047#include <sysutils/NetlinkEvent.h>
48
Kenny Root344ca102012-04-03 17:23:01 -070049#include <private/android_filesystem_config.h>
50
Paul Crowleyc6433a22017-10-24 14:54:43 -070051#include <ext4_utils/ext4_crypt.h>
52
53#include "Devmapper.h"
54#include "Ext4Crypt.h"
San Mehata19b2502010-01-06 10:33:53 -080055#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070056#include "NetlinkManager.h"
57#include "Process.h"
58#include "Utils.h"
59#include "VoldUtil.h"
60#include "VolumeManager.h"
61#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070062#include "fs/Ext4.h"
63#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070064#include "model/EmulatedVolume.h"
65#include "model/ObbVolume.h"
San Mehat23969932010-01-09 07:08:06 -080066
Jeff Sharkey36801cc2015-03-13 16:09:20 -070067using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060068using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070069
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060070static const char* kPathUserMount = "/mnt/user";
71static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
72
73static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
74
75/* 512MiB is large enough for testing purposes */
76static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070077
Jeff Sharkey36801cc2015-03-13 16:09:20 -070078static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080079static const unsigned int kMajorBlockExperimentalMin = 240;
80static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070081
San Mehatf1b736b2009-10-10 17:22:08 -070082VolumeManager *VolumeManager::sInstance = NULL;
83
84VolumeManager *VolumeManager::Instance() {
85 if (!sInstance)
86 sInstance = new VolumeManager();
87 return sInstance;
88}
89
90VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080091 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060092 mNextObbId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -070093 // For security reasons, assume that a secure keyguard is
94 // showing until we hear otherwise
95 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -070096}
97
98VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080099}
100
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600101int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600102 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600103 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600104 if (access(kPathVirtualDisk, F_OK) != 0) {
105 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
106 }
107
108 if (mVirtualDisk == nullptr) {
109 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
110 LOG(ERROR) << "Failed to create virtual disk";
111 return -1;
112 }
113
114 struct stat buf;
115 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
116 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
117 return -1;
118 }
119
120 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
121 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600122 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700123 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600124 }
125 } else {
126 if (mVirtualDisk != nullptr) {
127 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700128 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129
130 Loop::destroyByDevice(mVirtualDiskPath.c_str());
131 mVirtualDisk = nullptr;
132 }
133
134 if (access(kPathVirtualDisk, F_OK) == 0) {
135 unlink(kPathVirtualDisk);
136 }
137 }
138 return 0;
139}
140
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700141int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800142 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700143 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800144}
145
San Mehatf1b736b2009-10-10 17:22:08 -0700146int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600147 ATRACE_NAME("VolumeManager::start");
148
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700149 // Always start from a clean slate by unmounting everything in
150 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700151 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700152
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600153 Devmapper::destroyAll();
154 Loop::destroyAll();
155
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700156 // Assume that we always have an emulated volume on internal
157 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700158 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700159 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700160 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700161 mInternalEmulated->create();
162
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600163 // Consider creating a virtual disk
164 updateVirtualDisk();
165
San Mehatf1b736b2009-10-10 17:22:08 -0700166 return 0;
167}
168
169int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700170 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700171 mInternalEmulated->destroy();
172 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700173 return 0;
174}
175
San Mehatfd7f5872009-10-12 11:32:47 -0700176void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700177 std::lock_guard<std::mutex> lock(mLock);
178
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700179 if (mDebug) {
180 LOG(VERBOSE) << "----------------";
181 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
182 evt->dump();
183 }
San Mehatf1b736b2009-10-10 17:22:08 -0700184
Mateusz Nowak64403792015-08-03 16:39:19 +0200185 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
186 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700187
188 if (devType != "disk") return;
189
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600190 int major = std::stoi(evt->findParam("MAJOR"));
191 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192 dev_t device = makedev(major, minor);
193
194 switch (evt->getAction()) {
195 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700196 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700197 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800198 // For now, assume that MMC and virtio-blk (the latter is
199 // emulator-specific; see Disk.cpp for details) devices are SD,
200 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700201 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800202 if (major == kMajorBlockMmc
203 || (android::vold::IsRunningInEmulator()
204 && major >= (int) kMajorBlockExperimentalMin
205 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700206 flags |= android::vold::Disk::Flags::kSd;
207 } else {
208 flags |= android::vold::Disk::Flags::kUsb;
209 }
210
211 auto disk = new android::vold::Disk(eventPath, device,
212 source->getNickname(), flags);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700213 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700214 break;
215 }
216 }
217 break;
218 }
219 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700220 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700221 handleDiskChanged(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700222 break;
223 }
224 case NetlinkEvent::Action::kRemove: {
Jeff Sharkey401b2602017-12-14 22:15:20 -0700225 handleDiskRemoved(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700226 break;
227 }
228 default: {
229 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
230 break;
231 }
232 }
233}
234
Jeff Sharkey401b2602017-12-14 22:15:20 -0700235void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
236 // For security reasons, if secure keyguard is showing, wait
237 // until the user unlocks the device to actually touch it
238 if (mSecureKeyguardShowing) {
239 LOG(INFO) << "Found disk at " << disk->getEventPath()
240 << " but delaying scan due to secure keyguard";
241 mPendingDisks.push_back(disk);
242 } else {
243 disk->create();
244 mDisks.push_back(disk);
245 }
246}
247
248void VolumeManager::handleDiskChanged(dev_t device) {
249 for (const auto& disk : mDisks) {
250 if (disk->getDevice() == device) {
251 disk->readMetadata();
252 disk->readPartitions();
253 }
254 }
255
256 // For security reasons, we ignore all pending disks, since
257 // we'll scan them once the device is unlocked
258}
259
260void VolumeManager::handleDiskRemoved(dev_t device) {
261 auto i = mDisks.begin();
262 while (i != mDisks.end()) {
263 if ((*i)->getDevice() == device) {
264 (*i)->destroy();
265 i = mDisks.erase(i);
266 } else {
267 ++i;
268 }
269 }
270 auto j = mPendingDisks.begin();
271 while (j != mPendingDisks.end()) {
272 if ((*j)->getDevice() == device) {
273 j = mPendingDisks.erase(j);
274 } else {
275 ++j;
276 }
277 }
278}
279
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700280void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800281 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700282 mDiskSources.push_back(diskSource);
283}
284
285std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
286 for (auto disk : mDisks) {
287 if (disk->getId() == id) {
288 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700289 }
290 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700291 return nullptr;
292}
San Mehatf1b736b2009-10-10 17:22:08 -0700293
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700294std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800295 // Vold could receive "mount" after "shutdown" command in the extreme case.
296 // If this happens, mInternalEmulated will equal nullptr and
297 // we need to deal with it in order to avoid null pointer crash.
298 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700299 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700300 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700301 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700302 auto vol = disk->findVolume(id);
303 if (vol != nullptr) {
304 return vol;
305 }
306 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600307 for (const auto& vol : mObbVolumes) {
308 if (vol->getId() == id) {
309 return vol;
310 }
311 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700312 return nullptr;
313}
314
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700315void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
316 std::list<std::string>& list) {
317 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700318 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700319 disk->listVolumes(type, list);
320 }
321}
322
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600323int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700324 std::string normalizedGuid;
325 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
326 LOG(WARNING) << "Invalid GUID " << partGuid;
327 return -1;
328 }
329
Paul Crowleyc6433a22017-10-24 14:54:43 -0700330 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700331 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
332 if (unlink(keyPath.c_str()) != 0) {
333 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700334 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700335 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700336 if (e4crypt_is_native()) {
337 if (!e4crypt_destroy_volume_keys(fsUuid)) {
338 success = false;
339 }
340 }
341 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700342}
343
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700344int VolumeManager::linkPrimary(userid_t userId) {
345 std::string source(mPrimary->getPath());
346 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
347 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700348 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700349 }
350
351 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
352 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
353 if (errno != ENOENT) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600354 PLOG(WARNING) << "Failed to unlink " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700355 }
356 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700357 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700358 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600359 PLOG(WARNING) << "Failed to link";
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700360 return -errno;
361 }
362 return 0;
363}
364
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700365int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
366 mAddedUsers[userId] = userSerialNumber;
367 return 0;
368}
369
370int VolumeManager::onUserRemoved(userid_t userId) {
371 mAddedUsers.erase(userId);
372 return 0;
373}
374
Sudheer Shankaebaad1c2018-07-31 16:39:59 -0700375int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700376 // Note that sometimes the system will spin up processes from Zygote
377 // before actually starting the user, so we're okay if Zygote
378 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600379 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700380 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
381
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700382 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700383 mUserPackages[userId] = packageNames;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700384 if (mPrimary) {
385 linkPrimary(userId);
386 }
387 return 0;
388}
389
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700390int VolumeManager::onUserStopped(userid_t userId) {
391 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700392 return 0;
393}
394
Sudheer Shankad484aa92018-07-31 10:07:34 -0700395int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
396 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700397 for (size_t i = 0; i < packageNames.size(); ++i) {
398 mAppIds[packageNames[i]] = appIds[i];
399 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700400 return 0;
401}
402
403int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
404 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700405 for (size_t i = 0; i < appIds.size(); ++i) {
406 mSandboxIds[appIds[i]] = sandboxIds[i];
407 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700408 return 0;
409}
410
Jeff Sharkey401b2602017-12-14 22:15:20 -0700411int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
412 mSecureKeyguardShowing = isShowing;
413 if (!mSecureKeyguardShowing) {
414 // Now that secure keyguard has been dismissed, process
415 // any pending disks
416 for (const auto& disk : mPendingDisks) {
417 disk->create();
418 mDisks.push_back(disk);
419 }
420 mPendingDisks.clear();
421 }
422 return 0;
423}
424
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700425int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
426 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700427 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700428 linkPrimary(userId);
429 }
430 return 0;
431}
432
Jeff Sharkey3472e522017-10-06 18:02:53 -0600433static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700434 FILE* fp = setmntent("/proc/mounts", "r");
435 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600436 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700437 return -errno;
438 }
439
440 // Some volumes can be stacked on each other, so force unmount in
441 // reverse order to give us the best chance of success.
442 std::list<std::string> toUnmount;
443 mntent* mentry;
444 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600445 auto test = std::string(mentry->mnt_dir) + "/";
Elliott Hughes32a5b9a2017-12-20 12:38:47 -0800446 if (android::base::StartsWith(test, prefix)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600447 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700448 }
449 }
450 endmntent(fp);
451
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700452 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700453 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600454 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700455 }
456 }
457 return 0;
458}
459
Jeff Sharkey66270a22015-06-24 11:49:24 -0700460int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
461 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
462
463 DIR* dir;
464 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600465 std::string rootName;
466 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700467 int pidFd;
468 int nsFd;
469 struct stat sb;
470 pid_t child;
471
472 if (!(dir = opendir("/proc"))) {
473 PLOG(ERROR) << "Failed to opendir";
474 return -1;
475 }
476
477 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600478 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
479 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700480 closedir(dir);
481 return -1;
482 }
483
484 // Poke through all running PIDs look for apps running as UID
485 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700486 pid_t pid;
487 if (de->d_type != DT_DIR) continue;
488 if (!android::base::ParseInt(de->d_name, &pid)) continue;
489
Jeff Sharkey66270a22015-06-24 11:49:24 -0700490 pidFd = -1;
491 nsFd = -1;
492
493 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
494 if (pidFd < 0) {
495 goto next;
496 }
497 if (fstat(pidFd, &sb) != 0) {
498 PLOG(WARNING) << "Failed to stat " << de->d_name;
499 goto next;
500 }
501 if (sb.st_uid != uid) {
502 goto next;
503 }
504
505 // Matches so far, but refuse to touch if in root namespace
506 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600507 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700508 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
509 goto next;
510 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600511 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700512 LOG(WARNING) << "Skipping due to root namespace";
513 goto next;
514 }
515
516 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600517 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700518 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700519 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700520 goto next;
521 }
522
523 if (!(child = fork())) {
524 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700525 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700526 _exit(1);
527 }
528
Jeff Sharkey3472e522017-10-06 18:02:53 -0600529 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700530
531 std::string storageSource;
532 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700533 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700534 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700535 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700536 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700537 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700538 } else {
539 // Sane default of no storage visible
540 _exit(0);
541 }
542 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900543 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700544 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
545 << de->d_name;
546 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700547 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900548 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
549 MS_REC | MS_SLAVE, NULL)) == -1) {
550 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
551 << de->d_name;
552 _exit(1);
553 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700554
555 // Mount user-specific symlink helper into place
556 userid_t user_id = multiuser_get_user_id(uid);
557 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
558 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
559 NULL, MS_BIND, NULL)) == -1) {
560 PLOG(ERROR) << "Failed to mount " << userSource << " for "
561 << de->d_name;
562 _exit(1);
563 }
564
Jeff Sharkey66270a22015-06-24 11:49:24 -0700565 _exit(0);
566 }
567
568 if (child == -1) {
569 PLOG(ERROR) << "Failed to fork";
570 goto next;
571 } else {
572 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
573 }
574
575next:
576 close(nsFd);
577 close(pidFd);
578 }
579 closedir(dir);
580 return 0;
581}
582
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700583int VolumeManager::reset() {
584 // Tear down all existing disks/volumes and start from a blank slate so
585 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800586 if (mInternalEmulated != nullptr) {
587 mInternalEmulated->destroy();
588 mInternalEmulated->create();
589 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700590 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700591 disk->destroy();
592 disk->create();
593 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600594 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700595 mAddedUsers.clear();
596 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700597
598 mUserPackages.clear();
599 mAppIds.clear();
600 mSandboxIds.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700601 return 0;
602}
603
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700604// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700605int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700606 if (mInternalEmulated == nullptr) {
607 return 0; // already shutdown
608 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700609 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700610 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700611 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700612 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700613 disk->destroy();
614 }
615 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700616 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700617 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700618 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700619}
620
Jeff Sharkey9c484982015-03-31 10:35:33 -0700621int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700622 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600623 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700624
Jeff Sharkey9c484982015-03-31 10:35:33 -0700625 // First, try gracefully unmounting all known devices
626 if (mInternalEmulated != nullptr) {
627 mInternalEmulated->unmount();
628 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700629 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700630 disk->unmountAll();
631 }
632
633 // Worst case we might have some stale mounts lurking around, so
634 // force unmount those just to be safe.
635 FILE* fp = setmntent("/proc/mounts", "r");
636 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600637 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700638 return -errno;
639 }
640
641 // Some volumes can be stacked on each other, so force unmount in
642 // reverse order to give us the best chance of success.
643 std::list<std::string> toUnmount;
644 mntent* mentry;
645 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600646 auto test = std::string(mentry->mnt_dir);
Tri Vobca5cd72018-04-16 14:27:10 -0700647 if ((android::base::StartsWith(test, "/mnt/") &&
Bowgo Tsaic0cd37b2018-06-29 10:31:07 +0800648 !android::base::StartsWith(test, "/mnt/vendor") &&
649 !android::base::StartsWith(test, "/mnt/product")) ||
Tri Vobca5cd72018-04-16 14:27:10 -0700650 android::base::StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600651 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700652 }
653 }
654 endmntent(fp);
655
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700656 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600657 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700658 android::vold::ForceUnmount(path);
659 }
660
661 return 0;
662}
663
Jeff Sharkey3472e522017-10-06 18:02:53 -0600664int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700665 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600666 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700667 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600668 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700669 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600670 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700671 return -EINVAL;
672 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700673}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600674
675static size_t kAppFuseMaxMountPointName = 32;
676
677static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
678 if (name.size() > kAppFuseMaxMountPointName) {
679 LOG(ERROR) << "AppFuse mount name is too long.";
680 return -EINVAL;
681 }
682 for (size_t i = 0; i < name.size(); i++) {
683 if (!isalnum(name[i])) {
684 LOG(ERROR) << "AppFuse mount name contains invalid character.";
685 return -EINVAL;
686 }
687 }
688 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
689 return android::OK;
690}
691
692static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
693 // Remove existing mount.
694 android::vold::ForceUnmount(path);
695
696 const auto opts = android::base::StringPrintf(
697 "fd=%i,"
698 "rootmode=40000,"
699 "default_permissions,"
700 "allow_other,"
701 "user_id=%d,group_id=%d,"
702 "context=\"u:object_r:app_fuse_file:s0\","
703 "fscontext=u:object_r:app_fusefs:s0",
704 device_fd,
705 uid,
706 uid);
707
708 const int result = TEMP_FAILURE_RETRY(mount(
709 "/dev/fuse", path.c_str(), "fuse",
710 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
711 if (result != 0) {
712 PLOG(ERROR) << "Failed to mount " << path;
713 return -errno;
714 }
715
716 return android::OK;
717}
718
719static android::status_t runCommandInNamespace(const std::string& command,
720 uid_t uid,
721 pid_t pid,
722 const std::string& path,
723 int device_fd) {
724 if (DEBUG_APPFUSE) {
725 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
726 << " in namespace " << uid;
727 }
728
729 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
730 if (dir.get() == -1) {
731 PLOG(ERROR) << "Failed to open /proc";
732 return -errno;
733 }
734
735 // Obtains process file descriptor.
736 const std::string pid_str = android::base::StringPrintf("%d", pid);
737 const unique_fd pid_fd(
738 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
739 if (pid_fd.get() == -1) {
740 PLOG(ERROR) << "Failed to open /proc/" << pid;
741 return -errno;
742 }
743
744 // Check UID of process.
745 {
746 struct stat sb;
747 const int result = fstat(pid_fd.get(), &sb);
748 if (result == -1) {
749 PLOG(ERROR) << "Failed to stat /proc/" << pid;
750 return -errno;
751 }
752 if (sb.st_uid != AID_SYSTEM) {
753 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
754 << ", actual=" << sb.st_uid;
755 return -EPERM;
756 }
757 }
758
759 // Matches so far, but refuse to touch if in root namespace
760 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600761 std::string rootName;
762 std::string pidName;
763 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
764 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
765 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600766 return -EPERM;
767 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600768 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600769 LOG(ERROR) << "Don't mount appfuse in root namespace";
770 return -EPERM;
771 }
772 }
773
774 // We purposefully leave the namespace open across the fork
775 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
776 if (ns_fd.get() < 0) {
777 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
778 return -errno;
779 }
780
781 int child = fork();
782 if (child == 0) {
783 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
784 PLOG(ERROR) << "Failed to setns";
785 _exit(-errno);
786 }
787
788 if (command == "mount") {
789 _exit(mountInNamespace(uid, device_fd, path));
790 } else if (command == "unmount") {
791 // If it's just after all FD opened on mount point are closed, umount2 can fail with
792 // EBUSY. To avoid the case, specify MNT_DETACH.
793 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
794 errno != EINVAL && errno != ENOENT) {
795 PLOG(ERROR) << "Failed to unmount directory.";
796 _exit(-errno);
797 }
798 if (rmdir(path.c_str()) != 0) {
799 PLOG(ERROR) << "Failed to remove the mount directory.";
800 _exit(-errno);
801 }
802 _exit(android::OK);
803 } else {
804 LOG(ERROR) << "Unknown appfuse command " << command;
805 _exit(-EPERM);
806 }
807 }
808
809 if (child == -1) {
810 PLOG(ERROR) << "Failed to folk child process";
811 return -errno;
812 }
813
814 android::status_t status;
815 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
816
817 return status;
818}
819
820int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
821 int32_t ownerGid, std::string* outVolId) {
822 int id = mNextObbId++;
823
824 auto vol = std::shared_ptr<android::vold::VolumeBase>(
825 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
826 vol->create();
827
828 mObbVolumes.push_back(vol);
829 *outVolId = vol->getId();
830 return android::OK;
831}
832
833int VolumeManager::destroyObb(const std::string& volId) {
834 auto i = mObbVolumes.begin();
835 while (i != mObbVolumes.end()) {
836 if ((*i)->getId() == volId) {
837 (*i)->destroy();
838 i = mObbVolumes.erase(i);
839 } else {
840 ++i;
841 }
842 }
843 return android::OK;
844}
845
846int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
847 android::base::unique_fd* device_fd) {
848 std::string name = std::to_string(mountId);
849
850 // Check mount point name.
851 std::string path;
852 if (getMountPath(uid, name, &path) != android::OK) {
853 LOG(ERROR) << "Invalid mount point name";
854 return -1;
855 }
856
857 // Create directories.
858 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
859 if (result != android::OK) {
860 PLOG(ERROR) << "Failed to prepare directory " << path;
861 return -1;
862 }
863
864 // Open device FD.
865 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
866 if (device_fd->get() == -1) {
867 PLOG(ERROR) << "Failed to open /dev/fuse";
868 return -1;
869 }
870
871 // Mount.
872 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
873}
874
875int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
876 std::string name = std::to_string(mountId);
877
878 // Check mount point name.
879 std::string path;
880 if (getMountPath(uid, name, &path) != android::OK) {
881 LOG(ERROR) << "Invalid mount point name";
882 return -1;
883 }
884
885 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
886}