blob: c1d51d9f087c8644326252738c6e292243780b70 [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
Keun-young Park375ac252017-08-02 17:45:48 -070065bool VolumeManager::shutting_down = false;
66
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060067static const char* kPathUserMount = "/mnt/user";
68static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
69
70static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
71
72/* 512MiB is large enough for testing purposes */
73static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070074
Jeff Sharkey36801cc2015-03-13 16:09:20 -070075static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080076static const unsigned int kMajorBlockExperimentalMin = 240;
77static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070078
San Mehatf1b736b2009-10-10 17:22:08 -070079VolumeManager *VolumeManager::sInstance = NULL;
80
81VolumeManager *VolumeManager::Instance() {
82 if (!sInstance)
83 sInstance = new VolumeManager();
84 return sInstance;
85}
86
87VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080088 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060089 mNextObbId = 0;
San Mehatf1b736b2009-10-10 17:22:08 -070090}
91
92VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080093}
94
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060095int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -060096 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -060097 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060098 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 Sharkey67b8c492017-09-21 17:08:43 -0600151 ATRACE_NAME("VolumeManager::start");
152
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700153 // Always start from a clean slate by unmounting everything in
154 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700155 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700156
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600157 Devmapper::destroyAll();
158 Loop::destroyAll();
159
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700160 // Assume that we always have an emulated volume on internal
161 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700162 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700163 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700164 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700165 mInternalEmulated->create();
166
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600167 // Consider creating a virtual disk
168 updateVirtualDisk();
169
San Mehatf1b736b2009-10-10 17:22:08 -0700170 return 0;
171}
172
173int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700174 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700175 mInternalEmulated->destroy();
176 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700177 return 0;
178}
179
San Mehatfd7f5872009-10-12 11:32:47 -0700180void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700181 std::lock_guard<std::mutex> lock(mLock);
182
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700183 if (mDebug) {
184 LOG(VERBOSE) << "----------------";
185 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
186 evt->dump();
187 }
San Mehatf1b736b2009-10-10 17:22:08 -0700188
Mateusz Nowak64403792015-08-03 16:39:19 +0200189 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
190 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700191
192 if (devType != "disk") return;
193
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600194 int major = std::stoi(evt->findParam("MAJOR"));
195 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700196 dev_t device = makedev(major, minor);
197
198 switch (evt->getAction()) {
199 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700200 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700201 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800202 // For now, assume that MMC and virtio-blk (the latter is
203 // emulator-specific; see Disk.cpp for details) devices are SD,
204 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700205 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800206 if (major == kMajorBlockMmc
207 || (android::vold::IsRunningInEmulator()
208 && major >= (int) kMajorBlockExperimentalMin
209 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700210 flags |= android::vold::Disk::Flags::kSd;
211 } else {
212 flags |= android::vold::Disk::Flags::kUsb;
213 }
214
215 auto disk = new android::vold::Disk(eventPath, device,
216 source->getNickname(), flags);
217 disk->create();
218 mDisks.push_back(std::shared_ptr<android::vold::Disk>(disk));
219 break;
220 }
221 }
222 break;
223 }
224 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700225 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700226 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700227 if (disk->getDevice() == device) {
228 disk->readMetadata();
229 disk->readPartitions();
230 }
231 }
232 break;
233 }
234 case NetlinkEvent::Action::kRemove: {
235 auto i = mDisks.begin();
236 while (i != mDisks.end()) {
237 if ((*i)->getDevice() == device) {
238 (*i)->destroy();
239 i = mDisks.erase(i);
240 } else {
241 ++i;
242 }
243 }
244 break;
245 }
246 default: {
247 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
248 break;
249 }
250 }
251}
252
253void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800254 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700255 mDiskSources.push_back(diskSource);
256}
257
258std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
259 for (auto disk : mDisks) {
260 if (disk->getId() == id) {
261 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700262 }
263 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700264 return nullptr;
265}
San Mehatf1b736b2009-10-10 17:22:08 -0700266
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700267std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800268 // Vold could receive "mount" after "shutdown" command in the extreme case.
269 // If this happens, mInternalEmulated will equal nullptr and
270 // we need to deal with it in order to avoid null pointer crash.
271 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700272 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700273 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700274 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700275 auto vol = disk->findVolume(id);
276 if (vol != nullptr) {
277 return vol;
278 }
279 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600280 for (const auto& vol : mObbVolumes) {
281 if (vol->getId() == id) {
282 return vol;
283 }
284 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700285 return nullptr;
286}
287
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700288void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
289 std::list<std::string>& list) {
290 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700291 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700292 disk->listVolumes(type, list);
293 }
294}
295
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700296int VolumeManager::forgetPartition(const std::string& partGuid) {
297 std::string normalizedGuid;
298 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
299 LOG(WARNING) << "Invalid GUID " << partGuid;
300 return -1;
301 }
302
303 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
304 if (unlink(keyPath.c_str()) != 0) {
305 LOG(ERROR) << "Failed to unlink " << keyPath;
306 return -1;
307 }
308
309 return 0;
310}
311
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700312int VolumeManager::linkPrimary(userid_t userId) {
313 std::string source(mPrimary->getPath());
314 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
315 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700316 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700317 }
318
319 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
320 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
321 if (errno != ENOENT) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600322 PLOG(WARNING) << "Failed to unlink " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700323 }
324 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700325 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700326 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600327 PLOG(WARNING) << "Failed to link";
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700328 return -errno;
329 }
330 return 0;
331}
332
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700333int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
334 mAddedUsers[userId] = userSerialNumber;
335 return 0;
336}
337
338int VolumeManager::onUserRemoved(userid_t userId) {
339 mAddedUsers.erase(userId);
340 return 0;
341}
342
343int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700344 // Note that sometimes the system will spin up processes from Zygote
345 // before actually starting the user, so we're okay if Zygote
346 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600347 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700348 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
349
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700350 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700351 if (mPrimary) {
352 linkPrimary(userId);
353 }
354 return 0;
355}
356
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700357int VolumeManager::onUserStopped(userid_t userId) {
358 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700359 return 0;
360}
361
362int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
363 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700364 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700365 linkPrimary(userId);
366 }
367 return 0;
368}
369
Jeff Sharkey3472e522017-10-06 18:02:53 -0600370static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700371 FILE* fp = setmntent("/proc/mounts", "r");
372 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600373 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700374 return -errno;
375 }
376
377 // Some volumes can be stacked on each other, so force unmount in
378 // reverse order to give us the best chance of success.
379 std::list<std::string> toUnmount;
380 mntent* mentry;
381 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600382 auto test = std::string(mentry->mnt_dir) + "/";
383 if (android::base::StartsWith(test, prefix.c_str())) {
384 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700385 }
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)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600391 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700392 }
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;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600402 std::string rootName;
403 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700404 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
Jeff Sharkey3472e522017-10-06 18:02:53 -0600415 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
416 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700417 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;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600440 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700441 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
442 goto next;
443 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600444 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700445 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 Sharkey3472e522017-10-06 18:02:53 -0600462 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);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600551 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700552
Jeff Sharkey9c484982015-03-31 10:35:33 -0700553 // First, try gracefully unmounting all known devices
554 if (mInternalEmulated != nullptr) {
555 mInternalEmulated->unmount();
556 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700557 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700558 disk->unmountAll();
559 }
560
561 // Worst case we might have some stale mounts lurking around, so
562 // force unmount those just to be safe.
563 FILE* fp = setmntent("/proc/mounts", "r");
564 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600565 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700566 return -errno;
567 }
568
569 // Some volumes can be stacked on each other, so force unmount in
570 // reverse order to give us the best chance of success.
571 std::list<std::string> toUnmount;
572 mntent* mentry;
573 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600574 auto test = std::string(mentry->mnt_dir);
575 if (android::base::StartsWith(test, "/mnt/")
576 || android::base::StartsWith(test, "/storage/")) {
577 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700578 }
579 }
580 endmntent(fp);
581
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700582 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600583 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700584 android::vold::ForceUnmount(path);
585 }
586
587 return 0;
588}
589
Jeff Sharkey9c484982015-03-31 10:35:33 -0700590extern "C" int vold_unmountAll(void) {
Ken Sumrall425524d2012-06-14 20:55:28 -0700591 VolumeManager *vm = VolumeManager::Instance();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700592 return vm->unmountAll();
Ken Sumrall425524d2012-06-14 20:55:28 -0700593}
594
Jeff Sharkey3472e522017-10-06 18:02:53 -0600595int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700596 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600597 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700598 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600599 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700600 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600601 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700602 return -EINVAL;
603 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700604}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600605
606static size_t kAppFuseMaxMountPointName = 32;
607
608static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
609 if (name.size() > kAppFuseMaxMountPointName) {
610 LOG(ERROR) << "AppFuse mount name is too long.";
611 return -EINVAL;
612 }
613 for (size_t i = 0; i < name.size(); i++) {
614 if (!isalnum(name[i])) {
615 LOG(ERROR) << "AppFuse mount name contains invalid character.";
616 return -EINVAL;
617 }
618 }
619 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
620 return android::OK;
621}
622
623static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
624 // Remove existing mount.
625 android::vold::ForceUnmount(path);
626
627 const auto opts = android::base::StringPrintf(
628 "fd=%i,"
629 "rootmode=40000,"
630 "default_permissions,"
631 "allow_other,"
632 "user_id=%d,group_id=%d,"
633 "context=\"u:object_r:app_fuse_file:s0\","
634 "fscontext=u:object_r:app_fusefs:s0",
635 device_fd,
636 uid,
637 uid);
638
639 const int result = TEMP_FAILURE_RETRY(mount(
640 "/dev/fuse", path.c_str(), "fuse",
641 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
642 if (result != 0) {
643 PLOG(ERROR) << "Failed to mount " << path;
644 return -errno;
645 }
646
647 return android::OK;
648}
649
650static android::status_t runCommandInNamespace(const std::string& command,
651 uid_t uid,
652 pid_t pid,
653 const std::string& path,
654 int device_fd) {
655 if (DEBUG_APPFUSE) {
656 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
657 << " in namespace " << uid;
658 }
659
660 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
661 if (dir.get() == -1) {
662 PLOG(ERROR) << "Failed to open /proc";
663 return -errno;
664 }
665
666 // Obtains process file descriptor.
667 const std::string pid_str = android::base::StringPrintf("%d", pid);
668 const unique_fd pid_fd(
669 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
670 if (pid_fd.get() == -1) {
671 PLOG(ERROR) << "Failed to open /proc/" << pid;
672 return -errno;
673 }
674
675 // Check UID of process.
676 {
677 struct stat sb;
678 const int result = fstat(pid_fd.get(), &sb);
679 if (result == -1) {
680 PLOG(ERROR) << "Failed to stat /proc/" << pid;
681 return -errno;
682 }
683 if (sb.st_uid != AID_SYSTEM) {
684 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
685 << ", actual=" << sb.st_uid;
686 return -EPERM;
687 }
688 }
689
690 // Matches so far, but refuse to touch if in root namespace
691 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600692 std::string rootName;
693 std::string pidName;
694 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
695 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
696 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600697 return -EPERM;
698 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600699 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600700 LOG(ERROR) << "Don't mount appfuse in root namespace";
701 return -EPERM;
702 }
703 }
704
705 // We purposefully leave the namespace open across the fork
706 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
707 if (ns_fd.get() < 0) {
708 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
709 return -errno;
710 }
711
712 int child = fork();
713 if (child == 0) {
714 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
715 PLOG(ERROR) << "Failed to setns";
716 _exit(-errno);
717 }
718
719 if (command == "mount") {
720 _exit(mountInNamespace(uid, device_fd, path));
721 } else if (command == "unmount") {
722 // If it's just after all FD opened on mount point are closed, umount2 can fail with
723 // EBUSY. To avoid the case, specify MNT_DETACH.
724 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
725 errno != EINVAL && errno != ENOENT) {
726 PLOG(ERROR) << "Failed to unmount directory.";
727 _exit(-errno);
728 }
729 if (rmdir(path.c_str()) != 0) {
730 PLOG(ERROR) << "Failed to remove the mount directory.";
731 _exit(-errno);
732 }
733 _exit(android::OK);
734 } else {
735 LOG(ERROR) << "Unknown appfuse command " << command;
736 _exit(-EPERM);
737 }
738 }
739
740 if (child == -1) {
741 PLOG(ERROR) << "Failed to folk child process";
742 return -errno;
743 }
744
745 android::status_t status;
746 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
747
748 return status;
749}
750
751int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
752 int32_t ownerGid, std::string* outVolId) {
753 int id = mNextObbId++;
754
755 auto vol = std::shared_ptr<android::vold::VolumeBase>(
756 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
757 vol->create();
758
759 mObbVolumes.push_back(vol);
760 *outVolId = vol->getId();
761 return android::OK;
762}
763
764int VolumeManager::destroyObb(const std::string& volId) {
765 auto i = mObbVolumes.begin();
766 while (i != mObbVolumes.end()) {
767 if ((*i)->getId() == volId) {
768 (*i)->destroy();
769 i = mObbVolumes.erase(i);
770 } else {
771 ++i;
772 }
773 }
774 return android::OK;
775}
776
777int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
778 android::base::unique_fd* device_fd) {
779 std::string name = std::to_string(mountId);
780
781 // Check mount point name.
782 std::string path;
783 if (getMountPath(uid, name, &path) != android::OK) {
784 LOG(ERROR) << "Invalid mount point name";
785 return -1;
786 }
787
788 // Create directories.
789 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
790 if (result != android::OK) {
791 PLOG(ERROR) << "Failed to prepare directory " << path;
792 return -1;
793 }
794
795 // Open device FD.
796 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
797 if (device_fd->get() == -1) {
798 PLOG(ERROR) << "Failed to open /dev/fuse";
799 return -1;
800 }
801
802 // Mount.
803 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
804}
805
806int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
807 std::string name = std::to_string(mountId);
808
809 // Check mount point name.
810 std::string path;
811 if (getMountPath(uid, name, &path) != android::OK) {
812 LOG(ERROR) << "Invalid mount point name";
813 return -1;
814 }
815
816 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
817}