blob: e96b7ac457b44f0aed508980206085a444b09416 [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>
Kenny Root344ca102012-04-03 17:23:01 -070022#include <fts.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080023#include <mntent.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/ioctl.h>
28#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080029#include <sys/stat.h>
30#include <sys/types.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070031#include <sys/sysmacros.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070032#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080033#include <unistd.h>
San Mehata19b2502010-01-06 10:33:53 -080034
San Mehata2677e42009-12-13 10:40:18 -080035#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070036
37#define LOG_TAG "Vold"
38
Kenny Root7b18a7b2010-03-15 13:13:41 -070039#include <openssl/md5.h>
40
Elliott Hughes7e128fb2015-12-04 15:50:53 -080041#include <android-base/logging.h>
42#include <android-base/stringprintf.h>
Jeff Sharkey71ebe152013-09-17 17:24:38 -070043#include <cutils/fs.h>
San Mehatf1b736b2009-10-10 17:22:08 -070044#include <cutils/log.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060045#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070046
Robert Craigb9e3ba52014-02-04 10:53:00 -050047#include <selinux/android.h>
48
San Mehatfd7f5872009-10-12 11:32:47 -070049#include <sysutils/NetlinkEvent.h>
50
Kenny Root344ca102012-04-03 17:23:01 -070051#include <private/android_filesystem_config.h>
52
Jeff Sharkey11c2d382017-09-11 10:32:01 -060053#include "model/EmulatedVolume.h"
54#include "model/ObbVolume.h"
San Mehatf1b736b2009-10-10 17:22:08 -070055#include "VolumeManager.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070056#include "NetlinkManager.h"
San Mehata19b2502010-01-06 10:33:53 -080057#include "Loop.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070058#include "fs/Ext4.h"
59#include "fs/Vfat.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070060#include "Utils.h"
San Mehatb78a32c2010-01-10 13:02:12 -080061#include "Devmapper.h"
San Mehat586536c2010-02-16 17:12:00 -080062#include "Process.h"
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +090063#include "VoldUtil.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070064#include "cryptfs.h"
San Mehat23969932010-01-09 07:08:06 -080065
Jeff Sharkey36801cc2015-03-13 16:09:20 -070066using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060067using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070068
Keun-young Park375ac252017-08-02 17:45:48 -070069bool VolumeManager::shutting_down = false;
70
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060071static const char* kPathUserMount = "/mnt/user";
72static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
73
74static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
75
76/* 512MiB is large enough for testing purposes */
77static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070078
Jeff Sharkey36801cc2015-03-13 16:09:20 -070079static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080080static const unsigned int kMajorBlockExperimentalMin = 240;
81static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070082
San Mehatf1b736b2009-10-10 17:22:08 -070083VolumeManager *VolumeManager::sInstance = NULL;
84
85VolumeManager *VolumeManager::Instance() {
86 if (!sInstance)
87 sInstance = new VolumeManager();
88 return sInstance;
89}
90
91VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080092 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060093 mNextObbId = 0;
San Mehatf1b736b2009-10-10 17:22:08 -070094}
95
96VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080097}
98
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060099int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600100 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600101 if (property_get_bool(kPropVirtualDisk, false)) {
102 if (access(kPathVirtualDisk, F_OK) != 0) {
103 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
104 }
105
106 if (mVirtualDisk == nullptr) {
107 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
108 LOG(ERROR) << "Failed to create virtual disk";
109 return -1;
110 }
111
112 struct stat buf;
113 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
114 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
115 return -1;
116 }
117
118 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
119 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
120 disk->create();
121 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
122 mDisks.push_back(mVirtualDisk);
123 }
124 } else {
125 if (mVirtualDisk != nullptr) {
126 dev_t device = mVirtualDisk->getDevice();
127
128 auto i = mDisks.begin();
129 while (i != mDisks.end()) {
130 if ((*i)->getDevice() == device) {
131 (*i)->destroy();
132 i = mDisks.erase(i);
133 } else {
134 ++i;
135 }
136 }
137
138 Loop::destroyByDevice(mVirtualDiskPath.c_str());
139 mVirtualDisk = nullptr;
140 }
141
142 if (access(kPathVirtualDisk, F_OK) == 0) {
143 unlink(kPathVirtualDisk);
144 }
145 }
146 return 0;
147}
148
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700149int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800150 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700151 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800152}
153
San Mehatf1b736b2009-10-10 17:22:08 -0700154int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600155 ATRACE_NAME("VolumeManager::start");
156
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700157 // Always start from a clean slate by unmounting everything in
158 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700159 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700160
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600161 Devmapper::destroyAll();
162 Loop::destroyAll();
163
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700164 // Assume that we always have an emulated volume on internal
165 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700166 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700167 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700168 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700169 mInternalEmulated->create();
170
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600171 // Consider creating a virtual disk
172 updateVirtualDisk();
173
San Mehatf1b736b2009-10-10 17:22:08 -0700174 return 0;
175}
176
177int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700178 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700179 mInternalEmulated->destroy();
180 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700181 return 0;
182}
183
San Mehatfd7f5872009-10-12 11:32:47 -0700184void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700185 std::lock_guard<std::mutex> lock(mLock);
186
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700187 if (mDebug) {
188 LOG(VERBOSE) << "----------------";
189 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
190 evt->dump();
191 }
San Mehatf1b736b2009-10-10 17:22:08 -0700192
Mateusz Nowak64403792015-08-03 16:39:19 +0200193 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
194 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700195
196 if (devType != "disk") return;
197
198 int major = atoi(evt->findParam("MAJOR"));
199 int minor = atoi(evt->findParam("MINOR"));
200 dev_t device = makedev(major, minor);
201
202 switch (evt->getAction()) {
203 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700204 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700205 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800206 // For now, assume that MMC and virtio-blk (the latter is
207 // emulator-specific; see Disk.cpp for details) devices are SD,
208 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700209 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800210 if (major == kMajorBlockMmc
211 || (android::vold::IsRunningInEmulator()
212 && major >= (int) kMajorBlockExperimentalMin
213 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700214 flags |= android::vold::Disk::Flags::kSd;
215 } else {
216 flags |= android::vold::Disk::Flags::kUsb;
217 }
218
219 auto disk = new android::vold::Disk(eventPath, device,
220 source->getNickname(), flags);
221 disk->create();
222 mDisks.push_back(std::shared_ptr<android::vold::Disk>(disk));
223 break;
224 }
225 }
226 break;
227 }
228 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700229 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700230 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700231 if (disk->getDevice() == device) {
232 disk->readMetadata();
233 disk->readPartitions();
234 }
235 }
236 break;
237 }
238 case NetlinkEvent::Action::kRemove: {
239 auto i = mDisks.begin();
240 while (i != mDisks.end()) {
241 if ((*i)->getDevice() == device) {
242 (*i)->destroy();
243 i = mDisks.erase(i);
244 } else {
245 ++i;
246 }
247 }
248 break;
249 }
250 default: {
251 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
252 break;
253 }
254 }
255}
256
257void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800258 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700259 mDiskSources.push_back(diskSource);
260}
261
262std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
263 for (auto disk : mDisks) {
264 if (disk->getId() == id) {
265 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700266 }
267 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700268 return nullptr;
269}
San Mehatf1b736b2009-10-10 17:22:08 -0700270
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700271std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800272 // Vold could receive "mount" after "shutdown" command in the extreme case.
273 // If this happens, mInternalEmulated will equal nullptr and
274 // we need to deal with it in order to avoid null pointer crash.
275 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700276 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700277 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700278 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700279 auto vol = disk->findVolume(id);
280 if (vol != nullptr) {
281 return vol;
282 }
283 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600284 for (const auto& vol : mObbVolumes) {
285 if (vol->getId() == id) {
286 return vol;
287 }
288 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700289 return nullptr;
290}
291
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700292void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
293 std::list<std::string>& list) {
294 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700295 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700296 disk->listVolumes(type, list);
297 }
298}
299
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700300int VolumeManager::forgetPartition(const std::string& partGuid) {
301 std::string normalizedGuid;
302 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
303 LOG(WARNING) << "Invalid GUID " << partGuid;
304 return -1;
305 }
306
307 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
308 if (unlink(keyPath.c_str()) != 0) {
309 LOG(ERROR) << "Failed to unlink " << keyPath;
310 return -1;
311 }
312
313 return 0;
314}
315
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700316int VolumeManager::linkPrimary(userid_t userId) {
317 std::string source(mPrimary->getPath());
318 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
319 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700320 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700321 }
322
323 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
324 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
325 if (errno != ENOENT) {
326 SLOGW("Failed to unlink %s: %s", target.c_str(), strerror(errno));
327 }
328 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700329 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700330 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
331 SLOGW("Failed to link %s to %s: %s", source.c_str(), target.c_str(),
332 strerror(errno));
333 return -errno;
334 }
335 return 0;
336}
337
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700338int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
339 mAddedUsers[userId] = userSerialNumber;
340 return 0;
341}
342
343int VolumeManager::onUserRemoved(userid_t userId) {
344 mAddedUsers.erase(userId);
345 return 0;
346}
347
348int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700349 // Note that sometimes the system will spin up processes from Zygote
350 // before actually starting the user, so we're okay if Zygote
351 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600352 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700353 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
354
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700355 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700356 if (mPrimary) {
357 linkPrimary(userId);
358 }
359 return 0;
360}
361
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700362int VolumeManager::onUserStopped(userid_t userId) {
363 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700364 return 0;
365}
366
367int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
368 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700369 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700370 linkPrimary(userId);
371 }
372 return 0;
373}
374
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700375static int unmount_tree(const char* path) {
376 size_t path_len = strlen(path);
377
378 FILE* fp = setmntent("/proc/mounts", "r");
379 if (fp == NULL) {
380 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
381 return -errno;
382 }
383
384 // Some volumes can be stacked on each other, so force unmount in
385 // reverse order to give us the best chance of success.
386 std::list<std::string> toUnmount;
387 mntent* mentry;
388 while ((mentry = getmntent(fp)) != NULL) {
389 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
390 toUnmount.push_front(std::string(mentry->mnt_dir));
391 }
392 }
393 endmntent(fp);
394
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700395 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700396 if (umount2(path.c_str(), MNT_DETACH)) {
397 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
398 }
399 }
400 return 0;
401}
402
Jeff Sharkey66270a22015-06-24 11:49:24 -0700403int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
404 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
405
406 DIR* dir;
407 struct dirent* de;
408 char rootName[PATH_MAX];
409 char pidName[PATH_MAX];
410 int pidFd;
411 int nsFd;
412 struct stat sb;
413 pid_t child;
414
415 if (!(dir = opendir("/proc"))) {
416 PLOG(ERROR) << "Failed to opendir";
417 return -1;
418 }
419
420 // Figure out root namespace to compare against below
Daichi Hirono10d34882016-01-29 14:33:51 +0900421 if (android::vold::SaneReadLinkAt(dirfd(dir), "1/ns/mnt", rootName, PATH_MAX) == -1) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700422 PLOG(ERROR) << "Failed to readlink";
423 closedir(dir);
424 return -1;
425 }
426
427 // Poke through all running PIDs look for apps running as UID
428 while ((de = readdir(dir))) {
429 pidFd = -1;
430 nsFd = -1;
431
432 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
433 if (pidFd < 0) {
434 goto next;
435 }
436 if (fstat(pidFd, &sb) != 0) {
437 PLOG(WARNING) << "Failed to stat " << de->d_name;
438 goto next;
439 }
440 if (sb.st_uid != uid) {
441 goto next;
442 }
443
444 // Matches so far, but refuse to touch if in root namespace
445 LOG(DEBUG) << "Found matching PID " << de->d_name;
Daichi Hirono10d34882016-01-29 14:33:51 +0900446 if (android::vold::SaneReadLinkAt(pidFd, "ns/mnt", pidName, PATH_MAX) == -1) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700447 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
448 goto next;
449 }
450 if (!strcmp(rootName, pidName)) {
451 LOG(WARNING) << "Skipping due to root namespace";
452 goto next;
453 }
454
455 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600456 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700457 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700458 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700459 goto next;
460 }
461
462 if (!(child = fork())) {
463 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700464 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700465 _exit(1);
466 }
467
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700468 unmount_tree("/storage");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700469
470 std::string storageSource;
471 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700472 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700473 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700474 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700475 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700476 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700477 } else {
478 // Sane default of no storage visible
479 _exit(0);
480 }
481 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900482 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700483 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
484 << de->d_name;
485 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700486 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900487 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
488 MS_REC | MS_SLAVE, NULL)) == -1) {
489 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
490 << de->d_name;
491 _exit(1);
492 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700493
494 // Mount user-specific symlink helper into place
495 userid_t user_id = multiuser_get_user_id(uid);
496 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
497 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
498 NULL, MS_BIND, NULL)) == -1) {
499 PLOG(ERROR) << "Failed to mount " << userSource << " for "
500 << de->d_name;
501 _exit(1);
502 }
503
Jeff Sharkey66270a22015-06-24 11:49:24 -0700504 _exit(0);
505 }
506
507 if (child == -1) {
508 PLOG(ERROR) << "Failed to fork";
509 goto next;
510 } else {
511 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
512 }
513
514next:
515 close(nsFd);
516 close(pidFd);
517 }
518 closedir(dir);
519 return 0;
520}
521
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700522int VolumeManager::reset() {
523 // Tear down all existing disks/volumes and start from a blank slate so
524 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800525 if (mInternalEmulated != nullptr) {
526 mInternalEmulated->destroy();
527 mInternalEmulated->create();
528 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700529 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700530 disk->destroy();
531 disk->create();
532 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600533 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700534 mAddedUsers.clear();
535 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700536 return 0;
537}
538
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700539// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700540int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700541 if (mInternalEmulated == nullptr) {
542 return 0; // already shutdown
543 }
Keun-young Park375ac252017-08-02 17:45:48 -0700544 shutting_down = true;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700545 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700546 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700547 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700548 disk->destroy();
549 }
550 mDisks.clear();
Keun-young Park375ac252017-08-02 17:45:48 -0700551 shutting_down = false;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700552 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700553}
554
Jeff Sharkey9c484982015-03-31 10:35:33 -0700555int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700556 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600557 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700558
Jeff Sharkey9c484982015-03-31 10:35:33 -0700559 // First, try gracefully unmounting all known devices
560 if (mInternalEmulated != nullptr) {
561 mInternalEmulated->unmount();
562 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700563 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700564 disk->unmountAll();
565 }
566
567 // Worst case we might have some stale mounts lurking around, so
568 // force unmount those just to be safe.
569 FILE* fp = setmntent("/proc/mounts", "r");
570 if (fp == NULL) {
571 SLOGE("Error opening /proc/mounts: %s", strerror(errno));
572 return -errno;
573 }
574
575 // Some volumes can be stacked on each other, so force unmount in
576 // reverse order to give us the best chance of success.
577 std::list<std::string> toUnmount;
578 mntent* mentry;
579 while ((mentry = getmntent(fp)) != NULL) {
580 if (strncmp(mentry->mnt_dir, "/mnt/", 5) == 0
581 || strncmp(mentry->mnt_dir, "/storage/", 9) == 0) {
582 toUnmount.push_front(std::string(mentry->mnt_dir));
583 }
584 }
585 endmntent(fp);
586
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700587 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600588 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700589 android::vold::ForceUnmount(path);
590 }
591
592 return 0;
593}
594
Jeff Sharkey9c484982015-03-31 10:35:33 -0700595extern "C" int vold_unmountAll(void) {
Ken Sumrall425524d2012-06-14 20:55:28 -0700596 VolumeManager *vm = VolumeManager::Instance();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700597 return vm->unmountAll();
Ken Sumrall425524d2012-06-14 20:55:28 -0700598}
599
Jeff Sharkey9462bdd2017-09-07 15:27:28 -0600600int VolumeManager::mkdirs(const char* path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700601 // Only offer to create directories for paths managed by vold
602 if (strncmp(path, "/storage/", 9) == 0) {
603 // fs_mkdirs() does symlink checking and relative path enforcement
604 return fs_mkdirs(path, 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700605 } else {
Cylen Yao27cfee32014-05-02 19:23:42 +0800606 SLOGE("Failed to find mounted volume for %s", path);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700607 return -EINVAL;
608 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700609}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600610
611static size_t kAppFuseMaxMountPointName = 32;
612
613static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
614 if (name.size() > kAppFuseMaxMountPointName) {
615 LOG(ERROR) << "AppFuse mount name is too long.";
616 return -EINVAL;
617 }
618 for (size_t i = 0; i < name.size(); i++) {
619 if (!isalnum(name[i])) {
620 LOG(ERROR) << "AppFuse mount name contains invalid character.";
621 return -EINVAL;
622 }
623 }
624 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
625 return android::OK;
626}
627
628static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
629 // Remove existing mount.
630 android::vold::ForceUnmount(path);
631
632 const auto opts = android::base::StringPrintf(
633 "fd=%i,"
634 "rootmode=40000,"
635 "default_permissions,"
636 "allow_other,"
637 "user_id=%d,group_id=%d,"
638 "context=\"u:object_r:app_fuse_file:s0\","
639 "fscontext=u:object_r:app_fusefs:s0",
640 device_fd,
641 uid,
642 uid);
643
644 const int result = TEMP_FAILURE_RETRY(mount(
645 "/dev/fuse", path.c_str(), "fuse",
646 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
647 if (result != 0) {
648 PLOG(ERROR) << "Failed to mount " << path;
649 return -errno;
650 }
651
652 return android::OK;
653}
654
655static android::status_t runCommandInNamespace(const std::string& command,
656 uid_t uid,
657 pid_t pid,
658 const std::string& path,
659 int device_fd) {
660 if (DEBUG_APPFUSE) {
661 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
662 << " in namespace " << uid;
663 }
664
665 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
666 if (dir.get() == -1) {
667 PLOG(ERROR) << "Failed to open /proc";
668 return -errno;
669 }
670
671 // Obtains process file descriptor.
672 const std::string pid_str = android::base::StringPrintf("%d", pid);
673 const unique_fd pid_fd(
674 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
675 if (pid_fd.get() == -1) {
676 PLOG(ERROR) << "Failed to open /proc/" << pid;
677 return -errno;
678 }
679
680 // Check UID of process.
681 {
682 struct stat sb;
683 const int result = fstat(pid_fd.get(), &sb);
684 if (result == -1) {
685 PLOG(ERROR) << "Failed to stat /proc/" << pid;
686 return -errno;
687 }
688 if (sb.st_uid != AID_SYSTEM) {
689 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
690 << ", actual=" << sb.st_uid;
691 return -EPERM;
692 }
693 }
694
695 // Matches so far, but refuse to touch if in root namespace
696 {
697 char rootName[PATH_MAX];
698 char pidName[PATH_MAX];
699 const int root_result =
700 android::vold::SaneReadLinkAt(dir.get(), "1/ns/mnt", rootName, PATH_MAX);
701 const int pid_result =
702 android::vold::SaneReadLinkAt(pid_fd.get(), "ns/mnt", pidName, PATH_MAX);
703 if (root_result == -1) {
704 LOG(ERROR) << "Failed to readlink for /proc/1/ns/mnt";
705 return -EPERM;
706 }
707 if (pid_result == -1) {
708 LOG(ERROR) << "Failed to readlink for /proc/" << pid << "/ns/mnt";
709 return -EPERM;
710 }
711 if (!strcmp(rootName, pidName)) {
712 LOG(ERROR) << "Don't mount appfuse in root namespace";
713 return -EPERM;
714 }
715 }
716
717 // We purposefully leave the namespace open across the fork
718 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
719 if (ns_fd.get() < 0) {
720 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
721 return -errno;
722 }
723
724 int child = fork();
725 if (child == 0) {
726 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
727 PLOG(ERROR) << "Failed to setns";
728 _exit(-errno);
729 }
730
731 if (command == "mount") {
732 _exit(mountInNamespace(uid, device_fd, path));
733 } else if (command == "unmount") {
734 // If it's just after all FD opened on mount point are closed, umount2 can fail with
735 // EBUSY. To avoid the case, specify MNT_DETACH.
736 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
737 errno != EINVAL && errno != ENOENT) {
738 PLOG(ERROR) << "Failed to unmount directory.";
739 _exit(-errno);
740 }
741 if (rmdir(path.c_str()) != 0) {
742 PLOG(ERROR) << "Failed to remove the mount directory.";
743 _exit(-errno);
744 }
745 _exit(android::OK);
746 } else {
747 LOG(ERROR) << "Unknown appfuse command " << command;
748 _exit(-EPERM);
749 }
750 }
751
752 if (child == -1) {
753 PLOG(ERROR) << "Failed to folk child process";
754 return -errno;
755 }
756
757 android::status_t status;
758 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
759
760 return status;
761}
762
763int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
764 int32_t ownerGid, std::string* outVolId) {
765 int id = mNextObbId++;
766
767 auto vol = std::shared_ptr<android::vold::VolumeBase>(
768 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
769 vol->create();
770
771 mObbVolumes.push_back(vol);
772 *outVolId = vol->getId();
773 return android::OK;
774}
775
776int VolumeManager::destroyObb(const std::string& volId) {
777 auto i = mObbVolumes.begin();
778 while (i != mObbVolumes.end()) {
779 if ((*i)->getId() == volId) {
780 (*i)->destroy();
781 i = mObbVolumes.erase(i);
782 } else {
783 ++i;
784 }
785 }
786 return android::OK;
787}
788
789int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
790 android::base::unique_fd* device_fd) {
791 std::string name = std::to_string(mountId);
792
793 // Check mount point name.
794 std::string path;
795 if (getMountPath(uid, name, &path) != android::OK) {
796 LOG(ERROR) << "Invalid mount point name";
797 return -1;
798 }
799
800 // Create directories.
801 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
802 if (result != android::OK) {
803 PLOG(ERROR) << "Failed to prepare directory " << path;
804 return -1;
805 }
806
807 // Open device FD.
808 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
809 if (device_fd->get() == -1) {
810 PLOG(ERROR) << "Failed to open /dev/fuse";
811 return -1;
812 }
813
814 // Mount.
815 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
816}
817
818int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
819 std::string name = std::to_string(mountId);
820
821 // Check mount point name.
822 std::string path;
823 if (getMountPath(uid, name, &path) != android::OK) {
824 LOG(ERROR) << "Invalid mount point name";
825 return -1;
826 }
827
828 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
829}