blob: 0a38e7a14a0e71858b946e63d67f857a078a870b [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)) {
Subhash Jadavanibb37cbc2017-07-06 15:53:24 -0700198 // For now, assume that MMC, virtio-blk (the latter is
199 // emulator-specific; see Disk.cpp for details) and UFS card
200 // devices are SD, 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
Subhash Jadavanibb37cbc2017-07-06 15:53:24 -0700203 || (eventPath.find("ufs") != std::string::npos)
Yu Ning942d4e82016-01-08 17:36:47 +0800204 || (android::vold::IsRunningInEmulator()
205 && major >= (int) kMajorBlockExperimentalMin
206 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700207 flags |= android::vold::Disk::Flags::kSd;
208 } else {
209 flags |= android::vold::Disk::Flags::kUsb;
210 }
211
Tom Marshallaf693242015-11-04 15:44:44 -0800212 android::vold::Disk* disk = (source->getPartNum() == -1) ?
213 new android::vold::Disk(eventPath, device,
214 source->getNickname(), flags) :
215 new android::vold::DiskPartition(eventPath, device,
216 source->getNickname(), flags,
Tom Marshalld18795d2015-11-05 11:20:54 -0800217 source->getPartNum(),
218 source->getFsType(), source->getMntOpts());
Jeff Sharkey401b2602017-12-14 22:15:20 -0700219 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700220 break;
221 }
222 }
223 break;
224 }
225 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700226 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700227 handleDiskChanged(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700228 break;
229 }
230 case NetlinkEvent::Action::kRemove: {
Jeff Sharkey401b2602017-12-14 22:15:20 -0700231 handleDiskRemoved(device);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700232 break;
233 }
234 default: {
235 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
236 break;
237 }
238 }
239}
240
Jeff Sharkey401b2602017-12-14 22:15:20 -0700241void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
242 // For security reasons, if secure keyguard is showing, wait
243 // until the user unlocks the device to actually touch it
244 if (mSecureKeyguardShowing) {
245 LOG(INFO) << "Found disk at " << disk->getEventPath()
246 << " but delaying scan due to secure keyguard";
247 mPendingDisks.push_back(disk);
248 } else {
249 disk->create();
250 mDisks.push_back(disk);
251 }
252}
253
254void VolumeManager::handleDiskChanged(dev_t device) {
255 for (const auto& disk : mDisks) {
256 if (disk->getDevice() == device) {
257 disk->readMetadata();
258 disk->readPartitions();
259 }
260 }
261
262 // For security reasons, we ignore all pending disks, since
263 // we'll scan them once the device is unlocked
264}
265
266void VolumeManager::handleDiskRemoved(dev_t device) {
267 auto i = mDisks.begin();
268 while (i != mDisks.end()) {
269 if ((*i)->getDevice() == device) {
270 (*i)->destroy();
271 i = mDisks.erase(i);
272 } else {
273 ++i;
274 }
275 }
276 auto j = mPendingDisks.begin();
277 while (j != mPendingDisks.end()) {
278 if ((*j)->getDevice() == device) {
279 j = mPendingDisks.erase(j);
280 } else {
281 ++j;
282 }
283 }
284}
285
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700286void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800287 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700288 mDiskSources.push_back(diskSource);
289}
290
291std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
292 for (auto disk : mDisks) {
293 if (disk->getId() == id) {
294 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700295 }
296 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700297 return nullptr;
298}
San Mehatf1b736b2009-10-10 17:22:08 -0700299
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700300std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800301 // Vold could receive "mount" after "shutdown" command in the extreme case.
302 // If this happens, mInternalEmulated will equal nullptr and
303 // we need to deal with it in order to avoid null pointer crash.
304 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700305 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700306 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700307 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700308 auto vol = disk->findVolume(id);
309 if (vol != nullptr) {
310 return vol;
311 }
312 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600313 for (const auto& vol : mObbVolumes) {
314 if (vol->getId() == id) {
315 return vol;
316 }
317 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700318 return nullptr;
319}
320
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700321void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
322 std::list<std::string>& list) {
323 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700324 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700325 disk->listVolumes(type, list);
326 }
327}
328
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600329int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700330 std::string normalizedGuid;
331 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
332 LOG(WARNING) << "Invalid GUID " << partGuid;
333 return -1;
334 }
335
Paul Crowleyc6433a22017-10-24 14:54:43 -0700336 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700337 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
338 if (unlink(keyPath.c_str()) != 0) {
339 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700340 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700341 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700342 if (e4crypt_is_native()) {
343 if (!e4crypt_destroy_volume_keys(fsUuid)) {
344 success = false;
345 }
346 }
347 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700348}
349
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700350int VolumeManager::linkPrimary(userid_t userId) {
351 std::string source(mPrimary->getPath());
352 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
353 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700354 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700355 }
356
357 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
358 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
359 if (errno != ENOENT) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600360 PLOG(WARNING) << "Failed to unlink " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700361 }
362 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700363 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700364 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600365 PLOG(WARNING) << "Failed to link";
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700366 return -errno;
367 }
368 return 0;
369}
370
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700371int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
372 mAddedUsers[userId] = userSerialNumber;
373 return 0;
374}
375
376int VolumeManager::onUserRemoved(userid_t userId) {
377 mAddedUsers.erase(userId);
378 return 0;
379}
380
381int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700382 // Note that sometimes the system will spin up processes from Zygote
383 // before actually starting the user, so we're okay if Zygote
384 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600385 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700386 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
387
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700388 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700389 if (mPrimary) {
390 linkPrimary(userId);
391 }
392 return 0;
393}
394
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700395int VolumeManager::onUserStopped(userid_t userId) {
396 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700397 return 0;
398}
399
Jeff Sharkey401b2602017-12-14 22:15:20 -0700400int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
401 mSecureKeyguardShowing = isShowing;
402 if (!mSecureKeyguardShowing) {
403 // Now that secure keyguard has been dismissed, process
404 // any pending disks
405 for (const auto& disk : mPendingDisks) {
406 disk->create();
407 mDisks.push_back(disk);
408 }
409 mPendingDisks.clear();
410 }
411 return 0;
412}
413
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700414int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
415 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700416 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700417 linkPrimary(userId);
418 }
419 return 0;
420}
421
Jeff Sharkey3472e522017-10-06 18:02:53 -0600422static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700423 FILE* fp = setmntent("/proc/mounts", "r");
424 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600425 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700426 return -errno;
427 }
428
429 // Some volumes can be stacked on each other, so force unmount in
430 // reverse order to give us the best chance of success.
431 std::list<std::string> toUnmount;
432 mntent* mentry;
433 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600434 auto test = std::string(mentry->mnt_dir) + "/";
Elliott Hughes32a5b9a2017-12-20 12:38:47 -0800435 if (android::base::StartsWith(test, prefix)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600436 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700437 }
438 }
439 endmntent(fp);
440
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700441 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700442 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600443 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700444 }
445 }
446 return 0;
447}
448
Jeff Sharkey66270a22015-06-24 11:49:24 -0700449int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
450 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
451
452 DIR* dir;
453 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600454 std::string rootName;
455 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700456 int pidFd;
457 int nsFd;
458 struct stat sb;
459 pid_t child;
460
461 if (!(dir = opendir("/proc"))) {
462 PLOG(ERROR) << "Failed to opendir";
463 return -1;
464 }
465
466 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600467 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
468 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700469 closedir(dir);
470 return -1;
471 }
472
473 // Poke through all running PIDs look for apps running as UID
474 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700475 pid_t pid;
476 if (de->d_type != DT_DIR) continue;
477 if (!android::base::ParseInt(de->d_name, &pid)) continue;
478
Jeff Sharkey66270a22015-06-24 11:49:24 -0700479 pidFd = -1;
480 nsFd = -1;
481
482 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
483 if (pidFd < 0) {
484 goto next;
485 }
486 if (fstat(pidFd, &sb) != 0) {
487 PLOG(WARNING) << "Failed to stat " << de->d_name;
488 goto next;
489 }
490 if (sb.st_uid != uid) {
491 goto next;
492 }
493
494 // Matches so far, but refuse to touch if in root namespace
495 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600496 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700497 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
498 goto next;
499 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600500 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700501 LOG(WARNING) << "Skipping due to root namespace";
502 goto next;
503 }
504
505 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600506 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700507 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700508 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700509 goto next;
510 }
511
512 if (!(child = fork())) {
513 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700514 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700515 _exit(1);
516 }
517
Jeff Sharkey3472e522017-10-06 18:02:53 -0600518 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700519
520 std::string storageSource;
521 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700522 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700523 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700524 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700525 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700526 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700527 } else {
528 // Sane default of no storage visible
529 _exit(0);
530 }
531 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900532 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700533 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
534 << de->d_name;
535 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700536 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900537 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
538 MS_REC | MS_SLAVE, NULL)) == -1) {
539 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
540 << de->d_name;
541 _exit(1);
542 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700543
544 // Mount user-specific symlink helper into place
545 userid_t user_id = multiuser_get_user_id(uid);
546 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
547 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
548 NULL, MS_BIND, NULL)) == -1) {
549 PLOG(ERROR) << "Failed to mount " << userSource << " for "
550 << de->d_name;
551 _exit(1);
552 }
553
Jeff Sharkey66270a22015-06-24 11:49:24 -0700554 _exit(0);
555 }
556
557 if (child == -1) {
558 PLOG(ERROR) << "Failed to fork";
559 goto next;
560 } else {
561 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
562 }
563
564next:
565 close(nsFd);
566 close(pidFd);
567 }
568 closedir(dir);
569 return 0;
570}
571
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700572int VolumeManager::reset() {
573 // Tear down all existing disks/volumes and start from a blank slate so
574 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800575 if (mInternalEmulated != nullptr) {
576 mInternalEmulated->destroy();
577 mInternalEmulated->create();
578 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700579 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700580 disk->destroy();
581 disk->create();
582 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600583 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700584 mAddedUsers.clear();
585 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700586 return 0;
587}
588
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700589// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700590int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700591 if (mInternalEmulated == nullptr) {
592 return 0; // already shutdown
593 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700594 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700595 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700596 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700597 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700598 disk->destroy();
599 }
600 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700601 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700602 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700603 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700604}
605
Jeff Sharkey9c484982015-03-31 10:35:33 -0700606int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700607 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600608 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700609
Jeff Sharkey9c484982015-03-31 10:35:33 -0700610 // First, try gracefully unmounting all known devices
611 if (mInternalEmulated != nullptr) {
612 mInternalEmulated->unmount();
613 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700614 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700615 disk->unmountAll();
616 }
617
618 // Worst case we might have some stale mounts lurking around, so
619 // force unmount those just to be safe.
620 FILE* fp = setmntent("/proc/mounts", "r");
621 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600622 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700623 return -errno;
624 }
625
626 // Some volumes can be stacked on each other, so force unmount in
627 // reverse order to give us the best chance of success.
628 std::list<std::string> toUnmount;
629 mntent* mentry;
630 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600631 auto test = std::string(mentry->mnt_dir);
Tri Vobca5cd72018-04-16 14:27:10 -0700632 if ((android::base::StartsWith(test, "/mnt/") &&
Jackeagle28b61922018-12-04 10:10:13 -0500633 !android::base::StartsWith(test, "/mnt/vendor")) ||
Tri Vobca5cd72018-04-16 14:27:10 -0700634 android::base::StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600635 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700636 }
637 }
638 endmntent(fp);
639
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700640 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600641 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700642 android::vold::ForceUnmount(path);
643 }
644
645 return 0;
646}
647
Jeff Sharkey3472e522017-10-06 18:02:53 -0600648int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700649 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600650 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700651 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600652 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700653 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600654 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700655 return -EINVAL;
656 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700657}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600658
659static size_t kAppFuseMaxMountPointName = 32;
660
661static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
662 if (name.size() > kAppFuseMaxMountPointName) {
663 LOG(ERROR) << "AppFuse mount name is too long.";
664 return -EINVAL;
665 }
666 for (size_t i = 0; i < name.size(); i++) {
667 if (!isalnum(name[i])) {
668 LOG(ERROR) << "AppFuse mount name contains invalid character.";
669 return -EINVAL;
670 }
671 }
672 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
673 return android::OK;
674}
675
676static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
677 // Remove existing mount.
678 android::vold::ForceUnmount(path);
679
680 const auto opts = android::base::StringPrintf(
681 "fd=%i,"
682 "rootmode=40000,"
683 "default_permissions,"
684 "allow_other,"
685 "user_id=%d,group_id=%d,"
686 "context=\"u:object_r:app_fuse_file:s0\","
687 "fscontext=u:object_r:app_fusefs:s0",
688 device_fd,
689 uid,
690 uid);
691
692 const int result = TEMP_FAILURE_RETRY(mount(
693 "/dev/fuse", path.c_str(), "fuse",
694 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
695 if (result != 0) {
696 PLOG(ERROR) << "Failed to mount " << path;
697 return -errno;
698 }
699
700 return android::OK;
701}
702
703static android::status_t runCommandInNamespace(const std::string& command,
704 uid_t uid,
705 pid_t pid,
706 const std::string& path,
707 int device_fd) {
708 if (DEBUG_APPFUSE) {
709 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
710 << " in namespace " << uid;
711 }
712
713 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
714 if (dir.get() == -1) {
715 PLOG(ERROR) << "Failed to open /proc";
716 return -errno;
717 }
718
719 // Obtains process file descriptor.
720 const std::string pid_str = android::base::StringPrintf("%d", pid);
721 const unique_fd pid_fd(
722 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
723 if (pid_fd.get() == -1) {
724 PLOG(ERROR) << "Failed to open /proc/" << pid;
725 return -errno;
726 }
727
728 // Check UID of process.
729 {
730 struct stat sb;
731 const int result = fstat(pid_fd.get(), &sb);
732 if (result == -1) {
733 PLOG(ERROR) << "Failed to stat /proc/" << pid;
734 return -errno;
735 }
736 if (sb.st_uid != AID_SYSTEM) {
737 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
738 << ", actual=" << sb.st_uid;
739 return -EPERM;
740 }
741 }
742
743 // Matches so far, but refuse to touch if in root namespace
744 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600745 std::string rootName;
746 std::string pidName;
747 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
748 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
749 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600750 return -EPERM;
751 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600752 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600753 LOG(ERROR) << "Don't mount appfuse in root namespace";
754 return -EPERM;
755 }
756 }
757
758 // We purposefully leave the namespace open across the fork
759 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
760 if (ns_fd.get() < 0) {
761 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
762 return -errno;
763 }
764
765 int child = fork();
766 if (child == 0) {
767 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
768 PLOG(ERROR) << "Failed to setns";
769 _exit(-errno);
770 }
771
772 if (command == "mount") {
773 _exit(mountInNamespace(uid, device_fd, path));
774 } else if (command == "unmount") {
775 // If it's just after all FD opened on mount point are closed, umount2 can fail with
776 // EBUSY. To avoid the case, specify MNT_DETACH.
777 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
778 errno != EINVAL && errno != ENOENT) {
779 PLOG(ERROR) << "Failed to unmount directory.";
780 _exit(-errno);
781 }
782 if (rmdir(path.c_str()) != 0) {
783 PLOG(ERROR) << "Failed to remove the mount directory.";
784 _exit(-errno);
785 }
786 _exit(android::OK);
787 } else {
788 LOG(ERROR) << "Unknown appfuse command " << command;
789 _exit(-EPERM);
790 }
791 }
792
793 if (child == -1) {
794 PLOG(ERROR) << "Failed to folk child process";
795 return -errno;
796 }
797
798 android::status_t status;
799 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
800
801 return status;
802}
803
804int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
805 int32_t ownerGid, std::string* outVolId) {
806 int id = mNextObbId++;
807
808 auto vol = std::shared_ptr<android::vold::VolumeBase>(
809 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
810 vol->create();
811
812 mObbVolumes.push_back(vol);
813 *outVolId = vol->getId();
814 return android::OK;
815}
816
817int VolumeManager::destroyObb(const std::string& volId) {
818 auto i = mObbVolumes.begin();
819 while (i != mObbVolumes.end()) {
820 if ((*i)->getId() == volId) {
821 (*i)->destroy();
822 i = mObbVolumes.erase(i);
823 } else {
824 ++i;
825 }
826 }
827 return android::OK;
828}
829
830int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
831 android::base::unique_fd* device_fd) {
832 std::string name = std::to_string(mountId);
833
834 // Check mount point name.
835 std::string path;
836 if (getMountPath(uid, name, &path) != android::OK) {
837 LOG(ERROR) << "Invalid mount point name";
838 return -1;
839 }
840
841 // Create directories.
842 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
843 if (result != android::OK) {
844 PLOG(ERROR) << "Failed to prepare directory " << path;
845 return -1;
846 }
847
848 // Open device FD.
849 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
850 if (device_fd->get() == -1) {
851 PLOG(ERROR) << "Failed to open /dev/fuse";
852 return -1;
853 }
854
855 // Mount.
856 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
857}
858
859int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
860 std::string name = std::to_string(mountId);
861
862 // Check mount point name.
863 std::string path;
864 if (getMountPath(uid, name, &path) != android::OK) {
865 LOG(ERROR) << "Invalid mount point name";
866 return -1;
867 }
868
869 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
870}