blob: 1847ab1a4abc6b4e7af2a57848e91953b9b517af [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 Sharkey3472e522017-10-06 18:02:53 -060037#include <android-base/properties.h>
38#include <android-base/strings.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/stringprintf.h>
Jeff Sharkey71ebe152013-09-17 17:24:38 -070040#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060041#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070042
Robert Craigb9e3ba52014-02-04 10:53:00 -050043#include <selinux/android.h>
44
San Mehatfd7f5872009-10-12 11:32:47 -070045#include <sysutils/NetlinkEvent.h>
46
Kenny Root344ca102012-04-03 17:23:01 -070047#include <private/android_filesystem_config.h>
48
Jeff Sharkey11c2d382017-09-11 10:32:01 -060049#include "model/EmulatedVolume.h"
50#include "model/ObbVolume.h"
San Mehatf1b736b2009-10-10 17:22:08 -070051#include "VolumeManager.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070052#include "NetlinkManager.h"
San Mehata19b2502010-01-06 10:33:53 -080053#include "Loop.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070054#include "fs/Ext4.h"
55#include "fs/Vfat.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070056#include "Utils.h"
San Mehatb78a32c2010-01-10 13:02:12 -080057#include "Devmapper.h"
San Mehat586536c2010-02-16 17:12:00 -080058#include "Process.h"
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +090059#include "VoldUtil.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070060#include "cryptfs.h"
San Mehat23969932010-01-09 07:08:06 -080061
Jeff Sharkey36801cc2015-03-13 16:09:20 -070062using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060063using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070064
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060065static const char* kPathUserMount = "/mnt/user";
66static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
67
68static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
69
70/* 512MiB is large enough for testing purposes */
71static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070072
Jeff Sharkey36801cc2015-03-13 16:09:20 -070073static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080074static const unsigned int kMajorBlockExperimentalMin = 240;
75static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070076
San Mehatf1b736b2009-10-10 17:22:08 -070077VolumeManager *VolumeManager::sInstance = NULL;
78
79VolumeManager *VolumeManager::Instance() {
80 if (!sInstance)
81 sInstance = new VolumeManager();
82 return sInstance;
83}
84
85VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080086 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060087 mNextObbId = 0;
San Mehatf1b736b2009-10-10 17:22:08 -070088}
89
90VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080091}
92
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060093int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -060094 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -060095 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060096 if (access(kPathVirtualDisk, F_OK) != 0) {
97 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
98 }
99
100 if (mVirtualDisk == nullptr) {
101 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
102 LOG(ERROR) << "Failed to create virtual disk";
103 return -1;
104 }
105
106 struct stat buf;
107 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
108 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
109 return -1;
110 }
111
112 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
113 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
114 disk->create();
115 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
116 mDisks.push_back(mVirtualDisk);
117 }
118 } else {
119 if (mVirtualDisk != nullptr) {
120 dev_t device = mVirtualDisk->getDevice();
121
122 auto i = mDisks.begin();
123 while (i != mDisks.end()) {
124 if ((*i)->getDevice() == device) {
125 (*i)->destroy();
126 i = mDisks.erase(i);
127 } else {
128 ++i;
129 }
130 }
131
132 Loop::destroyByDevice(mVirtualDiskPath.c_str());
133 mVirtualDisk = nullptr;
134 }
135
136 if (access(kPathVirtualDisk, F_OK) == 0) {
137 unlink(kPathVirtualDisk);
138 }
139 }
140 return 0;
141}
142
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700143int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800144 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700145 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800146}
147
San Mehatf1b736b2009-10-10 17:22:08 -0700148int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600149 ATRACE_NAME("VolumeManager::start");
150
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700151 // Always start from a clean slate by unmounting everything in
152 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700153 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700154
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600155 Devmapper::destroyAll();
156 Loop::destroyAll();
157
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700158 // Assume that we always have an emulated volume on internal
159 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700160 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700161 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700162 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700163 mInternalEmulated->create();
164
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600165 // Consider creating a virtual disk
166 updateVirtualDisk();
167
San Mehatf1b736b2009-10-10 17:22:08 -0700168 return 0;
169}
170
171int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700172 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700173 mInternalEmulated->destroy();
174 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700175 return 0;
176}
177
San Mehatfd7f5872009-10-12 11:32:47 -0700178void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700179 std::lock_guard<std::mutex> lock(mLock);
180
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700181 if (mDebug) {
182 LOG(VERBOSE) << "----------------";
183 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
184 evt->dump();
185 }
San Mehatf1b736b2009-10-10 17:22:08 -0700186
Mateusz Nowak64403792015-08-03 16:39:19 +0200187 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
188 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700189
190 if (devType != "disk") return;
191
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600192 int major = std::stoi(evt->findParam("MAJOR"));
193 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700194 dev_t device = makedev(major, minor);
195
196 switch (evt->getAction()) {
197 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700198 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700199 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800200 // For now, assume that MMC and virtio-blk (the latter is
201 // emulator-specific; see Disk.cpp for details) devices are SD,
202 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700203 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800204 if (major == kMajorBlockMmc
205 || (android::vold::IsRunningInEmulator()
206 && major >= (int) kMajorBlockExperimentalMin
207 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700208 flags |= android::vold::Disk::Flags::kSd;
209 } else {
210 flags |= android::vold::Disk::Flags::kUsb;
211 }
212
213 auto disk = new android::vold::Disk(eventPath, device,
214 source->getNickname(), flags);
215 disk->create();
216 mDisks.push_back(std::shared_ptr<android::vold::Disk>(disk));
217 break;
218 }
219 }
220 break;
221 }
222 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700223 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700224 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700225 if (disk->getDevice() == device) {
226 disk->readMetadata();
227 disk->readPartitions();
228 }
229 }
230 break;
231 }
232 case NetlinkEvent::Action::kRemove: {
233 auto i = mDisks.begin();
234 while (i != mDisks.end()) {
235 if ((*i)->getDevice() == device) {
236 (*i)->destroy();
237 i = mDisks.erase(i);
238 } else {
239 ++i;
240 }
241 }
242 break;
243 }
244 default: {
245 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
246 break;
247 }
248 }
249}
250
251void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800252 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700253 mDiskSources.push_back(diskSource);
254}
255
256std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
257 for (auto disk : mDisks) {
258 if (disk->getId() == id) {
259 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700260 }
261 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700262 return nullptr;
263}
San Mehatf1b736b2009-10-10 17:22:08 -0700264
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700265std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800266 // Vold could receive "mount" after "shutdown" command in the extreme case.
267 // If this happens, mInternalEmulated will equal nullptr and
268 // we need to deal with it in order to avoid null pointer crash.
269 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700270 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700271 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700272 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700273 auto vol = disk->findVolume(id);
274 if (vol != nullptr) {
275 return vol;
276 }
277 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600278 for (const auto& vol : mObbVolumes) {
279 if (vol->getId() == id) {
280 return vol;
281 }
282 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700283 return nullptr;
284}
285
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700286void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
287 std::list<std::string>& list) {
288 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700289 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700290 disk->listVolumes(type, list);
291 }
292}
293
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700294int VolumeManager::forgetPartition(const std::string& partGuid) {
295 std::string normalizedGuid;
296 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
297 LOG(WARNING) << "Invalid GUID " << partGuid;
298 return -1;
299 }
300
301 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
302 if (unlink(keyPath.c_str()) != 0) {
303 LOG(ERROR) << "Failed to unlink " << keyPath;
304 return -1;
305 }
306
307 return 0;
308}
309
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700310int VolumeManager::linkPrimary(userid_t userId) {
311 std::string source(mPrimary->getPath());
312 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
313 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700314 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700315 }
316
317 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
318 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
319 if (errno != ENOENT) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600320 PLOG(WARNING) << "Failed to unlink " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321 }
322 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700323 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700324 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600325 PLOG(WARNING) << "Failed to link";
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700326 return -errno;
327 }
328 return 0;
329}
330
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700331int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
332 mAddedUsers[userId] = userSerialNumber;
333 return 0;
334}
335
336int VolumeManager::onUserRemoved(userid_t userId) {
337 mAddedUsers.erase(userId);
338 return 0;
339}
340
341int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700342 // Note that sometimes the system will spin up processes from Zygote
343 // before actually starting the user, so we're okay if Zygote
344 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600345 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700346 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
347
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700348 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700349 if (mPrimary) {
350 linkPrimary(userId);
351 }
352 return 0;
353}
354
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700355int VolumeManager::onUserStopped(userid_t userId) {
356 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700357 return 0;
358}
359
360int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
361 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700362 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700363 linkPrimary(userId);
364 }
365 return 0;
366}
367
Jeff Sharkey3472e522017-10-06 18:02:53 -0600368static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700369 FILE* fp = setmntent("/proc/mounts", "r");
370 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600371 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700372 return -errno;
373 }
374
375 // Some volumes can be stacked on each other, so force unmount in
376 // reverse order to give us the best chance of success.
377 std::list<std::string> toUnmount;
378 mntent* mentry;
379 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600380 auto test = std::string(mentry->mnt_dir) + "/";
381 if (android::base::StartsWith(test, prefix.c_str())) {
382 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700383 }
384 }
385 endmntent(fp);
386
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700387 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700388 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600389 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700390 }
391 }
392 return 0;
393}
394
Jeff Sharkey66270a22015-06-24 11:49:24 -0700395int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
396 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
397
398 DIR* dir;
399 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600400 std::string rootName;
401 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700402 int pidFd;
403 int nsFd;
404 struct stat sb;
405 pid_t child;
406
407 if (!(dir = opendir("/proc"))) {
408 PLOG(ERROR) << "Failed to opendir";
409 return -1;
410 }
411
412 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600413 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
414 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700415 closedir(dir);
416 return -1;
417 }
418
419 // Poke through all running PIDs look for apps running as UID
420 while ((de = readdir(dir))) {
421 pidFd = -1;
422 nsFd = -1;
423
424 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
425 if (pidFd < 0) {
426 goto next;
427 }
428 if (fstat(pidFd, &sb) != 0) {
429 PLOG(WARNING) << "Failed to stat " << de->d_name;
430 goto next;
431 }
432 if (sb.st_uid != uid) {
433 goto next;
434 }
435
436 // Matches so far, but refuse to touch if in root namespace
437 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600438 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700439 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
440 goto next;
441 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600442 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700443 LOG(WARNING) << "Skipping due to root namespace";
444 goto next;
445 }
446
447 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600448 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700449 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700450 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700451 goto next;
452 }
453
454 if (!(child = fork())) {
455 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700456 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700457 _exit(1);
458 }
459
Jeff Sharkey3472e522017-10-06 18:02:53 -0600460 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700461
462 std::string storageSource;
463 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700464 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700465 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700466 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700467 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700468 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700469 } else {
470 // Sane default of no storage visible
471 _exit(0);
472 }
473 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900474 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700475 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
476 << de->d_name;
477 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700478 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900479 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
480 MS_REC | MS_SLAVE, NULL)) == -1) {
481 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
482 << de->d_name;
483 _exit(1);
484 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700485
486 // Mount user-specific symlink helper into place
487 userid_t user_id = multiuser_get_user_id(uid);
488 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
489 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
490 NULL, MS_BIND, NULL)) == -1) {
491 PLOG(ERROR) << "Failed to mount " << userSource << " for "
492 << de->d_name;
493 _exit(1);
494 }
495
Jeff Sharkey66270a22015-06-24 11:49:24 -0700496 _exit(0);
497 }
498
499 if (child == -1) {
500 PLOG(ERROR) << "Failed to fork";
501 goto next;
502 } else {
503 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
504 }
505
506next:
507 close(nsFd);
508 close(pidFd);
509 }
510 closedir(dir);
511 return 0;
512}
513
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700514int VolumeManager::reset() {
515 // Tear down all existing disks/volumes and start from a blank slate so
516 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800517 if (mInternalEmulated != nullptr) {
518 mInternalEmulated->destroy();
519 mInternalEmulated->create();
520 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700521 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700522 disk->destroy();
523 disk->create();
524 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600525 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700526 mAddedUsers.clear();
527 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700528 return 0;
529}
530
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700531// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700532int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700533 if (mInternalEmulated == nullptr) {
534 return 0; // already shutdown
535 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700536 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700537 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700538 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700539 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700540 disk->destroy();
541 }
542 mDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700543 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700544 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700545}
546
Jeff Sharkey9c484982015-03-31 10:35:33 -0700547int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700548 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600549 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700550
Jeff Sharkey9c484982015-03-31 10:35:33 -0700551 // First, try gracefully unmounting all known devices
552 if (mInternalEmulated != nullptr) {
553 mInternalEmulated->unmount();
554 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700555 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700556 disk->unmountAll();
557 }
558
559 // Worst case we might have some stale mounts lurking around, so
560 // force unmount those just to be safe.
561 FILE* fp = setmntent("/proc/mounts", "r");
562 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600563 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700564 return -errno;
565 }
566
567 // Some volumes can be stacked on each other, so force unmount in
568 // reverse order to give us the best chance of success.
569 std::list<std::string> toUnmount;
570 mntent* mentry;
571 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600572 auto test = std::string(mentry->mnt_dir);
573 if (android::base::StartsWith(test, "/mnt/")
574 || android::base::StartsWith(test, "/storage/")) {
575 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700576 }
577 }
578 endmntent(fp);
579
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700580 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600581 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700582 android::vold::ForceUnmount(path);
583 }
584
585 return 0;
586}
587
Jeff Sharkey9c484982015-03-31 10:35:33 -0700588extern "C" int vold_unmountAll(void) {
Ken Sumrall425524d2012-06-14 20:55:28 -0700589 VolumeManager *vm = VolumeManager::Instance();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700590 return vm->unmountAll();
Ken Sumrall425524d2012-06-14 20:55:28 -0700591}
592
Jeff Sharkey3472e522017-10-06 18:02:53 -0600593int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700594 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600595 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700596 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600597 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700598 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600599 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700600 return -EINVAL;
601 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700602}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600603
604static size_t kAppFuseMaxMountPointName = 32;
605
606static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
607 if (name.size() > kAppFuseMaxMountPointName) {
608 LOG(ERROR) << "AppFuse mount name is too long.";
609 return -EINVAL;
610 }
611 for (size_t i = 0; i < name.size(); i++) {
612 if (!isalnum(name[i])) {
613 LOG(ERROR) << "AppFuse mount name contains invalid character.";
614 return -EINVAL;
615 }
616 }
617 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
618 return android::OK;
619}
620
621static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
622 // Remove existing mount.
623 android::vold::ForceUnmount(path);
624
625 const auto opts = android::base::StringPrintf(
626 "fd=%i,"
627 "rootmode=40000,"
628 "default_permissions,"
629 "allow_other,"
630 "user_id=%d,group_id=%d,"
631 "context=\"u:object_r:app_fuse_file:s0\","
632 "fscontext=u:object_r:app_fusefs:s0",
633 device_fd,
634 uid,
635 uid);
636
637 const int result = TEMP_FAILURE_RETRY(mount(
638 "/dev/fuse", path.c_str(), "fuse",
639 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
640 if (result != 0) {
641 PLOG(ERROR) << "Failed to mount " << path;
642 return -errno;
643 }
644
645 return android::OK;
646}
647
648static android::status_t runCommandInNamespace(const std::string& command,
649 uid_t uid,
650 pid_t pid,
651 const std::string& path,
652 int device_fd) {
653 if (DEBUG_APPFUSE) {
654 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
655 << " in namespace " << uid;
656 }
657
658 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
659 if (dir.get() == -1) {
660 PLOG(ERROR) << "Failed to open /proc";
661 return -errno;
662 }
663
664 // Obtains process file descriptor.
665 const std::string pid_str = android::base::StringPrintf("%d", pid);
666 const unique_fd pid_fd(
667 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
668 if (pid_fd.get() == -1) {
669 PLOG(ERROR) << "Failed to open /proc/" << pid;
670 return -errno;
671 }
672
673 // Check UID of process.
674 {
675 struct stat sb;
676 const int result = fstat(pid_fd.get(), &sb);
677 if (result == -1) {
678 PLOG(ERROR) << "Failed to stat /proc/" << pid;
679 return -errno;
680 }
681 if (sb.st_uid != AID_SYSTEM) {
682 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
683 << ", actual=" << sb.st_uid;
684 return -EPERM;
685 }
686 }
687
688 // Matches so far, but refuse to touch if in root namespace
689 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600690 std::string rootName;
691 std::string pidName;
692 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
693 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
694 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600695 return -EPERM;
696 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600697 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600698 LOG(ERROR) << "Don't mount appfuse in root namespace";
699 return -EPERM;
700 }
701 }
702
703 // We purposefully leave the namespace open across the fork
704 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
705 if (ns_fd.get() < 0) {
706 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
707 return -errno;
708 }
709
710 int child = fork();
711 if (child == 0) {
712 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
713 PLOG(ERROR) << "Failed to setns";
714 _exit(-errno);
715 }
716
717 if (command == "mount") {
718 _exit(mountInNamespace(uid, device_fd, path));
719 } else if (command == "unmount") {
720 // If it's just after all FD opened on mount point are closed, umount2 can fail with
721 // EBUSY. To avoid the case, specify MNT_DETACH.
722 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
723 errno != EINVAL && errno != ENOENT) {
724 PLOG(ERROR) << "Failed to unmount directory.";
725 _exit(-errno);
726 }
727 if (rmdir(path.c_str()) != 0) {
728 PLOG(ERROR) << "Failed to remove the mount directory.";
729 _exit(-errno);
730 }
731 _exit(android::OK);
732 } else {
733 LOG(ERROR) << "Unknown appfuse command " << command;
734 _exit(-EPERM);
735 }
736 }
737
738 if (child == -1) {
739 PLOG(ERROR) << "Failed to folk child process";
740 return -errno;
741 }
742
743 android::status_t status;
744 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
745
746 return status;
747}
748
749int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
750 int32_t ownerGid, std::string* outVolId) {
751 int id = mNextObbId++;
752
753 auto vol = std::shared_ptr<android::vold::VolumeBase>(
754 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
755 vol->create();
756
757 mObbVolumes.push_back(vol);
758 *outVolId = vol->getId();
759 return android::OK;
760}
761
762int VolumeManager::destroyObb(const std::string& volId) {
763 auto i = mObbVolumes.begin();
764 while (i != mObbVolumes.end()) {
765 if ((*i)->getId() == volId) {
766 (*i)->destroy();
767 i = mObbVolumes.erase(i);
768 } else {
769 ++i;
770 }
771 }
772 return android::OK;
773}
774
775int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
776 android::base::unique_fd* device_fd) {
777 std::string name = std::to_string(mountId);
778
779 // Check mount point name.
780 std::string path;
781 if (getMountPath(uid, name, &path) != android::OK) {
782 LOG(ERROR) << "Invalid mount point name";
783 return -1;
784 }
785
786 // Create directories.
787 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
788 if (result != android::OK) {
789 PLOG(ERROR) << "Failed to prepare directory " << path;
790 return -1;
791 }
792
793 // Open device FD.
794 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
795 if (device_fd->get() == -1) {
796 PLOG(ERROR) << "Failed to open /dev/fuse";
797 return -1;
798 }
799
800 // Mount.
801 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
802}
803
804int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
805 std::string name = std::to_string(mountId);
806
807 // Check mount point name.
808 std::string path;
809 if (getMountPath(uid, name, &path) != android::OK) {
810 LOG(ERROR) << "Invalid mount point name";
811 return -1;
812 }
813
814 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
815}