blob: 6bed2bf0f454d759344822a94509b2ba3c9ac36f [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
Yabin Cuid1104f72015-01-02 13:28:28 -080017#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070018#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080019#include <fcntl.h>
Kenny Root344ca102012-04-03 17:23:01 -070020#include <fts.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080021#include <mntent.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <sys/ioctl.h>
26#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080027#include <sys/stat.h>
28#include <sys/types.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070029#include <sys/sysmacros.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070030#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080031#include <unistd.h>
San Mehata19b2502010-01-06 10:33:53 -080032
San Mehata2677e42009-12-13 10:40:18 -080033#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070034
35#define LOG_TAG "Vold"
36
Kenny Root7b18a7b2010-03-15 13:13:41 -070037#include <openssl/md5.h>
38
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/logging.h>
40#include <android-base/stringprintf.h>
Jeff Sharkey71ebe152013-09-17 17:24:38 -070041#include <cutils/fs.h>
San Mehatf1b736b2009-10-10 17:22:08 -070042#include <cutils/log.h>
43
Robert Craigb9e3ba52014-02-04 10:53:00 -050044#include <selinux/android.h>
45
San Mehatfd7f5872009-10-12 11:32:47 -070046#include <sysutils/NetlinkEvent.h>
47
Kenny Root344ca102012-04-03 17:23:01 -070048#include <private/android_filesystem_config.h>
49
Jeff Sharkey11c2d382017-09-11 10:32:01 -060050#include "model/EmulatedVolume.h"
51#include "model/ObbVolume.h"
San Mehatf1b736b2009-10-10 17:22:08 -070052#include "VolumeManager.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070053#include "NetlinkManager.h"
San Mehata19b2502010-01-06 10:33:53 -080054#include "Loop.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070055#include "fs/Ext4.h"
56#include "fs/Vfat.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070057#include "Utils.h"
San Mehatb78a32c2010-01-10 13:02:12 -080058#include "Devmapper.h"
San Mehat586536c2010-02-16 17:12:00 -080059#include "Process.h"
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +090060#include "VoldUtil.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070061#include "cryptfs.h"
San Mehat23969932010-01-09 07:08:06 -080062
Jeff Sharkey36801cc2015-03-13 16:09:20 -070063using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060064using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070065
Keun-young Park375ac252017-08-02 17:45:48 -070066bool VolumeManager::shutting_down = false;
67
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060068static const char* kPathUserMount = "/mnt/user";
69static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
70
71static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
72
73/* 512MiB is large enough for testing purposes */
74static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070075
Jeff Sharkey36801cc2015-03-13 16:09:20 -070076static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080077static const unsigned int kMajorBlockExperimentalMin = 240;
78static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070079
San Mehatf1b736b2009-10-10 17:22:08 -070080VolumeManager *VolumeManager::sInstance = NULL;
81
82VolumeManager *VolumeManager::Instance() {
83 if (!sInstance)
84 sInstance = new VolumeManager();
85 return sInstance;
86}
87
88VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080089 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060090 mNextObbId = 0;
San Mehatf1b736b2009-10-10 17:22:08 -070091}
92
93VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080094}
95
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060096int VolumeManager::updateVirtualDisk() {
97 if (property_get_bool(kPropVirtualDisk, false)) {
98 if (access(kPathVirtualDisk, F_OK) != 0) {
99 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
100 }
101
102 if (mVirtualDisk == nullptr) {
103 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
104 LOG(ERROR) << "Failed to create virtual disk";
105 return -1;
106 }
107
108 struct stat buf;
109 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
110 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
111 return -1;
112 }
113
114 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
115 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
116 disk->create();
117 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
118 mDisks.push_back(mVirtualDisk);
119 }
120 } else {
121 if (mVirtualDisk != nullptr) {
122 dev_t device = mVirtualDisk->getDevice();
123
124 auto i = mDisks.begin();
125 while (i != mDisks.end()) {
126 if ((*i)->getDevice() == device) {
127 (*i)->destroy();
128 i = mDisks.erase(i);
129 } else {
130 ++i;
131 }
132 }
133
134 Loop::destroyByDevice(mVirtualDiskPath.c_str());
135 mVirtualDisk = nullptr;
136 }
137
138 if (access(kPathVirtualDisk, F_OK) == 0) {
139 unlink(kPathVirtualDisk);
140 }
141 }
142 return 0;
143}
144
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700145int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800146 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700147 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800148}
149
San Mehatf1b736b2009-10-10 17:22:08 -0700150int VolumeManager::start() {
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) {
320 SLOGW("Failed to unlink %s: %s", target.c_str(), strerror(errno));
321 }
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()))) {
325 SLOGW("Failed to link %s to %s: %s", source.c_str(), target.c_str(),
326 strerror(errno));
327 return -errno;
328 }
329 return 0;
330}
331
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700332int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
333 mAddedUsers[userId] = userSerialNumber;
334 return 0;
335}
336
337int VolumeManager::onUserRemoved(userid_t userId) {
338 mAddedUsers.erase(userId);
339 return 0;
340}
341
342int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700343 // Note that sometimes the system will spin up processes from Zygote
344 // before actually starting the user, so we're okay if Zygote
345 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600346 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700347 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
348
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700349 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700350 if (mPrimary) {
351 linkPrimary(userId);
352 }
353 return 0;
354}
355
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700356int VolumeManager::onUserStopped(userid_t userId) {
357 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700358 return 0;
359}
360
361int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
362 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700363 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700364 linkPrimary(userId);
365 }
366 return 0;
367}
368
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700369static int unmount_tree(const char* path) {
370 size_t path_len = strlen(path);
371
372 FILE* fp = setmntent("/proc/mounts", "r");
373 if (fp == NULL) {
374 ALOGE("Error opening /proc/mounts: %s", strerror(errno));
375 return -errno;
376 }
377
378 // Some volumes can be stacked on each other, so force unmount in
379 // reverse order to give us the best chance of success.
380 std::list<std::string> toUnmount;
381 mntent* mentry;
382 while ((mentry = getmntent(fp)) != NULL) {
383 if (strncmp(mentry->mnt_dir, path, path_len) == 0) {
384 toUnmount.push_front(std::string(mentry->mnt_dir));
385 }
386 }
387 endmntent(fp);
388
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700389 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700390 if (umount2(path.c_str(), MNT_DETACH)) {
391 ALOGW("Failed to unmount %s: %s", path.c_str(), strerror(errno));
392 }
393 }
394 return 0;
395}
396
Jeff Sharkey66270a22015-06-24 11:49:24 -0700397int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
398 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
399
400 DIR* dir;
401 struct dirent* de;
402 char rootName[PATH_MAX];
403 char pidName[PATH_MAX];
404 int pidFd;
405 int nsFd;
406 struct stat sb;
407 pid_t child;
408
409 if (!(dir = opendir("/proc"))) {
410 PLOG(ERROR) << "Failed to opendir";
411 return -1;
412 }
413
414 // Figure out root namespace to compare against below
Daichi Hirono10d34882016-01-29 14:33:51 +0900415 if (android::vold::SaneReadLinkAt(dirfd(dir), "1/ns/mnt", rootName, PATH_MAX) == -1) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700416 PLOG(ERROR) << "Failed to readlink";
417 closedir(dir);
418 return -1;
419 }
420
421 // Poke through all running PIDs look for apps running as UID
422 while ((de = readdir(dir))) {
423 pidFd = -1;
424 nsFd = -1;
425
426 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
427 if (pidFd < 0) {
428 goto next;
429 }
430 if (fstat(pidFd, &sb) != 0) {
431 PLOG(WARNING) << "Failed to stat " << de->d_name;
432 goto next;
433 }
434 if (sb.st_uid != uid) {
435 goto next;
436 }
437
438 // Matches so far, but refuse to touch if in root namespace
439 LOG(DEBUG) << "Found matching PID " << de->d_name;
Daichi Hirono10d34882016-01-29 14:33:51 +0900440 if (android::vold::SaneReadLinkAt(pidFd, "ns/mnt", pidName, PATH_MAX) == -1) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700441 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
442 goto next;
443 }
444 if (!strcmp(rootName, pidName)) {
445 LOG(WARNING) << "Skipping due to root namespace";
446 goto next;
447 }
448
449 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600450 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700451 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700452 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700453 goto next;
454 }
455
456 if (!(child = fork())) {
457 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700458 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700459 _exit(1);
460 }
461
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700462 unmount_tree("/storage");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700463
464 std::string storageSource;
465 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700466 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700467 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700468 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700469 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700470 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700471 } else {
472 // Sane default of no storage visible
473 _exit(0);
474 }
475 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900476 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700477 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
478 << de->d_name;
479 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700480 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900481 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
482 MS_REC | MS_SLAVE, NULL)) == -1) {
483 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
484 << de->d_name;
485 _exit(1);
486 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700487
488 // Mount user-specific symlink helper into place
489 userid_t user_id = multiuser_get_user_id(uid);
490 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
491 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
492 NULL, MS_BIND, NULL)) == -1) {
493 PLOG(ERROR) << "Failed to mount " << userSource << " for "
494 << de->d_name;
495 _exit(1);
496 }
497
Jeff Sharkey66270a22015-06-24 11:49:24 -0700498 _exit(0);
499 }
500
501 if (child == -1) {
502 PLOG(ERROR) << "Failed to fork";
503 goto next;
504 } else {
505 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
506 }
507
508next:
509 close(nsFd);
510 close(pidFd);
511 }
512 closedir(dir);
513 return 0;
514}
515
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700516int VolumeManager::reset() {
517 // Tear down all existing disks/volumes and start from a blank slate so
518 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800519 if (mInternalEmulated != nullptr) {
520 mInternalEmulated->destroy();
521 mInternalEmulated->create();
522 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700523 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700524 disk->destroy();
525 disk->create();
526 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600527 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700528 mAddedUsers.clear();
529 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700530 return 0;
531}
532
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700533// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700534int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700535 if (mInternalEmulated == nullptr) {
536 return 0; // already shutdown
537 }
Keun-young Park375ac252017-08-02 17:45:48 -0700538 shutting_down = true;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700539 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700540 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700541 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700542 disk->destroy();
543 }
544 mDisks.clear();
Keun-young Park375ac252017-08-02 17:45:48 -0700545 shutting_down = false;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700546 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700547}
548
Jeff Sharkey9c484982015-03-31 10:35:33 -0700549int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700550 std::lock_guard<std::mutex> lock(mLock);
551
Jeff Sharkey9c484982015-03-31 10:35:33 -0700552 // First, try gracefully unmounting all known devices
553 if (mInternalEmulated != nullptr) {
554 mInternalEmulated->unmount();
555 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700556 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700557 disk->unmountAll();
558 }
559
560 // Worst case we might have some stale mounts lurking around, so
561 // force unmount those just to be safe.
562 FILE* fp = setmntent("/proc/mounts", "r");
563 if (fp == NULL) {
564 SLOGE("Error opening /proc/mounts: %s", strerror(errno));
565 return -errno;
566 }
567
568 // Some volumes can be stacked on each other, so force unmount in
569 // reverse order to give us the best chance of success.
570 std::list<std::string> toUnmount;
571 mntent* mentry;
572 while ((mentry = getmntent(fp)) != NULL) {
573 if (strncmp(mentry->mnt_dir, "/mnt/", 5) == 0
574 || strncmp(mentry->mnt_dir, "/storage/", 9) == 0) {
575 toUnmount.push_front(std::string(mentry->mnt_dir));
576 }
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 Sharkey9462bdd2017-09-07 15:27:28 -0600593int VolumeManager::mkdirs(const char* path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700594 // Only offer to create directories for paths managed by vold
595 if (strncmp(path, "/storage/", 9) == 0) {
596 // fs_mkdirs() does symlink checking and relative path enforcement
597 return fs_mkdirs(path, 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700598 } else {
Cylen Yao27cfee32014-05-02 19:23:42 +0800599 SLOGE("Failed to find mounted volume for %s", 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 {
690 char rootName[PATH_MAX];
691 char pidName[PATH_MAX];
692 const int root_result =
693 android::vold::SaneReadLinkAt(dir.get(), "1/ns/mnt", rootName, PATH_MAX);
694 const int pid_result =
695 android::vold::SaneReadLinkAt(pid_fd.get(), "ns/mnt", pidName, PATH_MAX);
696 if (root_result == -1) {
697 LOG(ERROR) << "Failed to readlink for /proc/1/ns/mnt";
698 return -EPERM;
699 }
700 if (pid_result == -1) {
701 LOG(ERROR) << "Failed to readlink for /proc/" << pid << "/ns/mnt";
702 return -EPERM;
703 }
704 if (!strcmp(rootName, pidName)) {
705 LOG(ERROR) << "Don't mount appfuse in root namespace";
706 return -EPERM;
707 }
708 }
709
710 // We purposefully leave the namespace open across the fork
711 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
712 if (ns_fd.get() < 0) {
713 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
714 return -errno;
715 }
716
717 int child = fork();
718 if (child == 0) {
719 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
720 PLOG(ERROR) << "Failed to setns";
721 _exit(-errno);
722 }
723
724 if (command == "mount") {
725 _exit(mountInNamespace(uid, device_fd, path));
726 } else if (command == "unmount") {
727 // If it's just after all FD opened on mount point are closed, umount2 can fail with
728 // EBUSY. To avoid the case, specify MNT_DETACH.
729 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
730 errno != EINVAL && errno != ENOENT) {
731 PLOG(ERROR) << "Failed to unmount directory.";
732 _exit(-errno);
733 }
734 if (rmdir(path.c_str()) != 0) {
735 PLOG(ERROR) << "Failed to remove the mount directory.";
736 _exit(-errno);
737 }
738 _exit(android::OK);
739 } else {
740 LOG(ERROR) << "Unknown appfuse command " << command;
741 _exit(-EPERM);
742 }
743 }
744
745 if (child == -1) {
746 PLOG(ERROR) << "Failed to folk child process";
747 return -errno;
748 }
749
750 android::status_t status;
751 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
752
753 return status;
754}
755
756int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
757 int32_t ownerGid, std::string* outVolId) {
758 int id = mNextObbId++;
759
760 auto vol = std::shared_ptr<android::vold::VolumeBase>(
761 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
762 vol->create();
763
764 mObbVolumes.push_back(vol);
765 *outVolId = vol->getId();
766 return android::OK;
767}
768
769int VolumeManager::destroyObb(const std::string& volId) {
770 auto i = mObbVolumes.begin();
771 while (i != mObbVolumes.end()) {
772 if ((*i)->getId() == volId) {
773 (*i)->destroy();
774 i = mObbVolumes.erase(i);
775 } else {
776 ++i;
777 }
778 }
779 return android::OK;
780}
781
782int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
783 android::base::unique_fd* device_fd) {
784 std::string name = std::to_string(mountId);
785
786 // Check mount point name.
787 std::string path;
788 if (getMountPath(uid, name, &path) != android::OK) {
789 LOG(ERROR) << "Invalid mount point name";
790 return -1;
791 }
792
793 // Create directories.
794 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
795 if (result != android::OK) {
796 PLOG(ERROR) << "Failed to prepare directory " << path;
797 return -1;
798 }
799
800 // Open device FD.
801 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
802 if (device_fd->get() == -1) {
803 PLOG(ERROR) << "Failed to open /dev/fuse";
804 return -1;
805 }
806
807 // Mount.
808 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
809}
810
811int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
812 std::string name = std::to_string(mountId);
813
814 // Check mount point name.
815 std::string path;
816 if (getMountPath(uid, name, &path) != android::OK) {
817 LOG(ERROR) << "Invalid mount point name";
818 return -1;
819 }
820
821 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
822}