blob: e078c0da3587ac22bfdc5f9d1bdafefdb6458d43 [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;
San Mehatf1b736b2009-10-10 17:22:08 -070093}
94
95VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080096}
97
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060098int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -060099 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600100 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600101 if (access(kPathVirtualDisk, F_OK) != 0) {
102 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
103 }
104
105 if (mVirtualDisk == nullptr) {
106 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
107 LOG(ERROR) << "Failed to create virtual disk";
108 return -1;
109 }
110
111 struct stat buf;
112 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
113 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
114 return -1;
115 }
116
117 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
118 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
119 disk->create();
120 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
121 mDisks.push_back(mVirtualDisk);
122 }
123 } else {
124 if (mVirtualDisk != nullptr) {
125 dev_t device = mVirtualDisk->getDevice();
126
127 auto i = mDisks.begin();
128 while (i != mDisks.end()) {
129 if ((*i)->getDevice() == device) {
130 (*i)->destroy();
131 i = mDisks.erase(i);
132 } else {
133 ++i;
134 }
135 }
136
137 Loop::destroyByDevice(mVirtualDiskPath.c_str());
138 mVirtualDisk = nullptr;
139 }
140
141 if (access(kPathVirtualDisk, F_OK) == 0) {
142 unlink(kPathVirtualDisk);
143 }
144 }
145 return 0;
146}
147
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700148int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800149 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700150 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800151}
152
San Mehatf1b736b2009-10-10 17:22:08 -0700153int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600154 ATRACE_NAME("VolumeManager::start");
155
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700156 // Always start from a clean slate by unmounting everything in
157 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700158 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700159
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600160 Devmapper::destroyAll();
161 Loop::destroyAll();
162
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700163 // Assume that we always have an emulated volume on internal
164 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700165 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700166 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700167 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700168 mInternalEmulated->create();
169
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600170 // Consider creating a virtual disk
171 updateVirtualDisk();
172
San Mehatf1b736b2009-10-10 17:22:08 -0700173 return 0;
174}
175
176int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700177 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700178 mInternalEmulated->destroy();
179 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700180 return 0;
181}
182
San Mehatfd7f5872009-10-12 11:32:47 -0700183void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700184 std::lock_guard<std::mutex> lock(mLock);
185
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700186 if (mDebug) {
187 LOG(VERBOSE) << "----------------";
188 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
189 evt->dump();
190 }
San Mehatf1b736b2009-10-10 17:22:08 -0700191
Mateusz Nowak64403792015-08-03 16:39:19 +0200192 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
193 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194
195 if (devType != "disk") return;
196
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600197 int major = std::stoi(evt->findParam("MAJOR"));
198 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700199 dev_t device = makedev(major, minor);
200
201 switch (evt->getAction()) {
202 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700203 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700204 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800205 // For now, assume that MMC and virtio-blk (the latter is
206 // emulator-specific; see Disk.cpp for details) devices are SD,
207 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700208 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800209 if (major == kMajorBlockMmc
210 || (android::vold::IsRunningInEmulator()
211 && major >= (int) kMajorBlockExperimentalMin
212 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700213 flags |= android::vold::Disk::Flags::kSd;
214 } else {
215 flags |= android::vold::Disk::Flags::kUsb;
216 }
217
218 auto disk = new android::vold::Disk(eventPath, device,
219 source->getNickname(), flags);
220 disk->create();
221 mDisks.push_back(std::shared_ptr<android::vold::Disk>(disk));
222 break;
223 }
224 }
225 break;
226 }
227 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700228 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700229 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700230 if (disk->getDevice() == device) {
231 disk->readMetadata();
232 disk->readPartitions();
233 }
234 }
235 break;
236 }
237 case NetlinkEvent::Action::kRemove: {
238 auto i = mDisks.begin();
239 while (i != mDisks.end()) {
240 if ((*i)->getDevice() == device) {
241 (*i)->destroy();
242 i = mDisks.erase(i);
243 } else {
244 ++i;
245 }
246 }
247 break;
248 }
249 default: {
250 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
251 break;
252 }
253 }
254}
255
256void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800257 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700258 mDiskSources.push_back(diskSource);
259}
260
261std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
262 for (auto disk : mDisks) {
263 if (disk->getId() == id) {
264 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700265 }
266 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700267 return nullptr;
268}
San Mehatf1b736b2009-10-10 17:22:08 -0700269
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700270std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800271 // Vold could receive "mount" after "shutdown" command in the extreme case.
272 // If this happens, mInternalEmulated will equal nullptr and
273 // we need to deal with it in order to avoid null pointer crash.
274 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700275 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700276 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700277 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700278 auto vol = disk->findVolume(id);
279 if (vol != nullptr) {
280 return vol;
281 }
282 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600283 for (const auto& vol : mObbVolumes) {
284 if (vol->getId() == id) {
285 return vol;
286 }
287 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700288 return nullptr;
289}
290
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700291void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
292 std::list<std::string>& list) {
293 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700294 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700295 disk->listVolumes(type, list);
296 }
297}
298
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600299int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700300 std::string normalizedGuid;
301 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
302 LOG(WARNING) << "Invalid GUID " << partGuid;
303 return -1;
304 }
305
Paul Crowleyc6433a22017-10-24 14:54:43 -0700306 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700307 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
308 if (unlink(keyPath.c_str()) != 0) {
309 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700310 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700311 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700312 if (e4crypt_is_native()) {
313 if (!e4crypt_destroy_volume_keys(fsUuid)) {
314 success = false;
315 }
316 }
317 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700318}
319
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700320int VolumeManager::linkPrimary(userid_t userId) {
321 std::string source(mPrimary->getPath());
322 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
323 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700324 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700325 }
326
327 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
328 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
329 if (errno != ENOENT) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600330 PLOG(WARNING) << "Failed to unlink " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700331 }
332 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700333 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700334 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600335 PLOG(WARNING) << "Failed to link";
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700336 return -errno;
337 }
338 return 0;
339}
340
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700341int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
342 mAddedUsers[userId] = userSerialNumber;
343 return 0;
344}
345
346int VolumeManager::onUserRemoved(userid_t userId) {
347 mAddedUsers.erase(userId);
348 return 0;
349}
350
351int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700352 // Note that sometimes the system will spin up processes from Zygote
353 // before actually starting the user, so we're okay if Zygote
354 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600355 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700356 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
357
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700358 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700359 if (mPrimary) {
360 linkPrimary(userId);
361 }
362 return 0;
363}
364
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700365int VolumeManager::onUserStopped(userid_t userId) {
366 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700367 return 0;
368}
369
370int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
371 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700372 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700373 linkPrimary(userId);
374 }
375 return 0;
376}
377
Jeff Sharkey3472e522017-10-06 18:02:53 -0600378static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700379 FILE* fp = setmntent("/proc/mounts", "r");
380 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600381 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700382 return -errno;
383 }
384
385 // Some volumes can be stacked on each other, so force unmount in
386 // reverse order to give us the best chance of success.
387 std::list<std::string> toUnmount;
388 mntent* mentry;
389 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600390 auto test = std::string(mentry->mnt_dir) + "/";
391 if (android::base::StartsWith(test, prefix.c_str())) {
392 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700393 }
394 }
395 endmntent(fp);
396
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700397 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700398 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600399 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700400 }
401 }
402 return 0;
403}
404
Jeff Sharkey66270a22015-06-24 11:49:24 -0700405int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
406 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
407
408 DIR* dir;
409 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600410 std::string rootName;
411 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700412 int pidFd;
413 int nsFd;
414 struct stat sb;
415 pid_t child;
416
417 if (!(dir = opendir("/proc"))) {
418 PLOG(ERROR) << "Failed to opendir";
419 return -1;
420 }
421
422 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600423 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
424 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700425 closedir(dir);
426 return -1;
427 }
428
429 // Poke through all running PIDs look for apps running as UID
430 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700431 pid_t pid;
432 if (de->d_type != DT_DIR) continue;
433 if (!android::base::ParseInt(de->d_name, &pid)) continue;
434
Jeff Sharkey66270a22015-06-24 11:49:24 -0700435 pidFd = -1;
436 nsFd = -1;
437
438 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
439 if (pidFd < 0) {
440 goto next;
441 }
442 if (fstat(pidFd, &sb) != 0) {
443 PLOG(WARNING) << "Failed to stat " << de->d_name;
444 goto next;
445 }
446 if (sb.st_uid != uid) {
447 goto next;
448 }
449
450 // Matches so far, but refuse to touch if in root namespace
451 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600452 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700453 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
454 goto next;
455 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600456 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700457 LOG(WARNING) << "Skipping due to root namespace";
458 goto next;
459 }
460
461 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600462 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700463 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700464 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700465 goto next;
466 }
467
468 if (!(child = fork())) {
469 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700470 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700471 _exit(1);
472 }
473
Jeff Sharkey3472e522017-10-06 18:02:53 -0600474 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700475
476 std::string storageSource;
477 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700478 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700479 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700480 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700481 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700482 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700483 } else {
484 // Sane default of no storage visible
485 _exit(0);
486 }
487 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900488 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700489 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
490 << de->d_name;
491 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700492 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900493 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
494 MS_REC | MS_SLAVE, NULL)) == -1) {
495 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
496 << de->d_name;
497 _exit(1);
498 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700499
500 // Mount user-specific symlink helper into place
501 userid_t user_id = multiuser_get_user_id(uid);
502 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
503 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
504 NULL, MS_BIND, NULL)) == -1) {
505 PLOG(ERROR) << "Failed to mount " << userSource << " for "
506 << de->d_name;
507 _exit(1);
508 }
509
Jeff Sharkey66270a22015-06-24 11:49:24 -0700510 _exit(0);
511 }
512
513 if (child == -1) {
514 PLOG(ERROR) << "Failed to fork";
515 goto next;
516 } else {
517 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
518 }
519
520next:
521 close(nsFd);
522 close(pidFd);
523 }
524 closedir(dir);
525 return 0;
526}
527
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700528int VolumeManager::reset() {
529 // Tear down all existing disks/volumes and start from a blank slate so
530 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800531 if (mInternalEmulated != nullptr) {
532 mInternalEmulated->destroy();
533 mInternalEmulated->create();
534 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700535 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700536 disk->destroy();
537 disk->create();
538 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600539 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700540 mAddedUsers.clear();
541 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700542 return 0;
543}
544
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700545// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700546int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700547 if (mInternalEmulated == nullptr) {
548 return 0; // already shutdown
549 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700550 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700551 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700552 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700553 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700554 disk->destroy();
555 }
556 mDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700557 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700558 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700559}
560
Jeff Sharkey9c484982015-03-31 10:35:33 -0700561int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700562 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600563 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700564
Jeff Sharkey9c484982015-03-31 10:35:33 -0700565 // First, try gracefully unmounting all known devices
566 if (mInternalEmulated != nullptr) {
567 mInternalEmulated->unmount();
568 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700569 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700570 disk->unmountAll();
571 }
572
573 // Worst case we might have some stale mounts lurking around, so
574 // force unmount those just to be safe.
575 FILE* fp = setmntent("/proc/mounts", "r");
576 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600577 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700578 return -errno;
579 }
580
581 // Some volumes can be stacked on each other, so force unmount in
582 // reverse order to give us the best chance of success.
583 std::list<std::string> toUnmount;
584 mntent* mentry;
585 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600586 auto test = std::string(mentry->mnt_dir);
587 if (android::base::StartsWith(test, "/mnt/")
588 || android::base::StartsWith(test, "/storage/")) {
589 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700590 }
591 }
592 endmntent(fp);
593
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700594 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600595 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700596 android::vold::ForceUnmount(path);
597 }
598
599 return 0;
600}
601
Jeff Sharkey3472e522017-10-06 18:02:53 -0600602int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700603 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600604 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700605 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600606 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700607 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600608 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700609 return -EINVAL;
610 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700611}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600612
613static size_t kAppFuseMaxMountPointName = 32;
614
615static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
616 if (name.size() > kAppFuseMaxMountPointName) {
617 LOG(ERROR) << "AppFuse mount name is too long.";
618 return -EINVAL;
619 }
620 for (size_t i = 0; i < name.size(); i++) {
621 if (!isalnum(name[i])) {
622 LOG(ERROR) << "AppFuse mount name contains invalid character.";
623 return -EINVAL;
624 }
625 }
626 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
627 return android::OK;
628}
629
630static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
631 // Remove existing mount.
632 android::vold::ForceUnmount(path);
633
634 const auto opts = android::base::StringPrintf(
635 "fd=%i,"
636 "rootmode=40000,"
637 "default_permissions,"
638 "allow_other,"
639 "user_id=%d,group_id=%d,"
640 "context=\"u:object_r:app_fuse_file:s0\","
641 "fscontext=u:object_r:app_fusefs:s0",
642 device_fd,
643 uid,
644 uid);
645
646 const int result = TEMP_FAILURE_RETRY(mount(
647 "/dev/fuse", path.c_str(), "fuse",
648 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
649 if (result != 0) {
650 PLOG(ERROR) << "Failed to mount " << path;
651 return -errno;
652 }
653
654 return android::OK;
655}
656
657static android::status_t runCommandInNamespace(const std::string& command,
658 uid_t uid,
659 pid_t pid,
660 const std::string& path,
661 int device_fd) {
662 if (DEBUG_APPFUSE) {
663 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
664 << " in namespace " << uid;
665 }
666
667 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
668 if (dir.get() == -1) {
669 PLOG(ERROR) << "Failed to open /proc";
670 return -errno;
671 }
672
673 // Obtains process file descriptor.
674 const std::string pid_str = android::base::StringPrintf("%d", pid);
675 const unique_fd pid_fd(
676 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
677 if (pid_fd.get() == -1) {
678 PLOG(ERROR) << "Failed to open /proc/" << pid;
679 return -errno;
680 }
681
682 // Check UID of process.
683 {
684 struct stat sb;
685 const int result = fstat(pid_fd.get(), &sb);
686 if (result == -1) {
687 PLOG(ERROR) << "Failed to stat /proc/" << pid;
688 return -errno;
689 }
690 if (sb.st_uid != AID_SYSTEM) {
691 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
692 << ", actual=" << sb.st_uid;
693 return -EPERM;
694 }
695 }
696
697 // Matches so far, but refuse to touch if in root namespace
698 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600699 std::string rootName;
700 std::string pidName;
701 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
702 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
703 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600704 return -EPERM;
705 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600706 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600707 LOG(ERROR) << "Don't mount appfuse in root namespace";
708 return -EPERM;
709 }
710 }
711
712 // We purposefully leave the namespace open across the fork
713 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
714 if (ns_fd.get() < 0) {
715 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
716 return -errno;
717 }
718
719 int child = fork();
720 if (child == 0) {
721 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
722 PLOG(ERROR) << "Failed to setns";
723 _exit(-errno);
724 }
725
726 if (command == "mount") {
727 _exit(mountInNamespace(uid, device_fd, path));
728 } else if (command == "unmount") {
729 // If it's just after all FD opened on mount point are closed, umount2 can fail with
730 // EBUSY. To avoid the case, specify MNT_DETACH.
731 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
732 errno != EINVAL && errno != ENOENT) {
733 PLOG(ERROR) << "Failed to unmount directory.";
734 _exit(-errno);
735 }
736 if (rmdir(path.c_str()) != 0) {
737 PLOG(ERROR) << "Failed to remove the mount directory.";
738 _exit(-errno);
739 }
740 _exit(android::OK);
741 } else {
742 LOG(ERROR) << "Unknown appfuse command " << command;
743 _exit(-EPERM);
744 }
745 }
746
747 if (child == -1) {
748 PLOG(ERROR) << "Failed to folk child process";
749 return -errno;
750 }
751
752 android::status_t status;
753 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
754
755 return status;
756}
757
758int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
759 int32_t ownerGid, std::string* outVolId) {
760 int id = mNextObbId++;
761
762 auto vol = std::shared_ptr<android::vold::VolumeBase>(
763 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
764 vol->create();
765
766 mObbVolumes.push_back(vol);
767 *outVolId = vol->getId();
768 return android::OK;
769}
770
771int VolumeManager::destroyObb(const std::string& volId) {
772 auto i = mObbVolumes.begin();
773 while (i != mObbVolumes.end()) {
774 if ((*i)->getId() == volId) {
775 (*i)->destroy();
776 i = mObbVolumes.erase(i);
777 } else {
778 ++i;
779 }
780 }
781 return android::OK;
782}
783
784int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
785 android::base::unique_fd* device_fd) {
786 std::string name = std::to_string(mountId);
787
788 // Check mount point name.
789 std::string path;
790 if (getMountPath(uid, name, &path) != android::OK) {
791 LOG(ERROR) << "Invalid mount point name";
792 return -1;
793 }
794
795 // Create directories.
796 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
797 if (result != android::OK) {
798 PLOG(ERROR) << "Failed to prepare directory " << path;
799 return -1;
800 }
801
802 // Open device FD.
803 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
804 if (device_fd->get() == -1) {
805 PLOG(ERROR) << "Failed to open /dev/fuse";
806 return -1;
807 }
808
809 // Mount.
810 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
811}
812
813int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
814 std::string name = std::to_string(mountId);
815
816 // Check mount point name.
817 std::string path;
818 if (getMountPath(uid, name, &path) != android::OK) {
819 LOG(ERROR) << "Invalid mount point name";
820 return -1;
821 }
822
823 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
824}