blob: 3194e5965a31821eaee9ec5224b79cf49b8da3c7 [file] [log] [blame]
San Mehatf1b736b2009-10-10 17:22:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey67b8c492017-09-21 17:08:43 -060017#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
Yabin Cuid1104f72015-01-02 13:28:28 -080019#include <dirent.h>
San Mehatf1b736b2009-10-10 17:22:08 -070020#include <errno.h>
San Mehata2677e42009-12-13 10:40:18 -080021#include <fcntl.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080022#include <mntent.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/mount.h>
San Mehata19b2502010-01-06 10:33:53 -080028#include <sys/stat.h>
29#include <sys/types.h>
Elliott Hughes0e08e842017-05-18 09:08:24 -070030#include <sys/sysmacros.h>
Jeff Sharkey66270a22015-06-24 11:49:24 -070031#include <sys/wait.h>
Yabin Cuid1104f72015-01-02 13:28:28 -080032#include <unistd.h>
San Mehata19b2502010-01-06 10:33:53 -080033
San Mehata2677e42009-12-13 10:40:18 -080034#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070035
Elliott Hughes7e128fb2015-12-04 15:50:53 -080036#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070037#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060038#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080039#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070040#include <android-base/strings.h>
41
Jeff Sharkey71ebe152013-09-17 17:24:38 -070042#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060043#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070044
Robert Craigb9e3ba52014-02-04 10:53:00 -050045#include <selinux/android.h>
46
San Mehatfd7f5872009-10-12 11:32:47 -070047#include <sysutils/NetlinkEvent.h>
48
Kenny Root344ca102012-04-03 17:23:01 -070049#include <private/android_filesystem_config.h>
50
Jeff Sharkey11c2d382017-09-11 10:32:01 -060051#include "model/EmulatedVolume.h"
52#include "model/ObbVolume.h"
San Mehatf1b736b2009-10-10 17:22:08 -070053#include "VolumeManager.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070054#include "NetlinkManager.h"
San Mehata19b2502010-01-06 10:33:53 -080055#include "Loop.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070056#include "fs/Ext4.h"
57#include "fs/Vfat.h"
Jeff Sharkey36801cc2015-03-13 16:09:20 -070058#include "Utils.h"
San Mehatb78a32c2010-01-10 13:02:12 -080059#include "Devmapper.h"
San Mehat586536c2010-02-16 17:12:00 -080060#include "Process.h"
Hiroaki Miyazawa14eab552015-02-04 13:29:15 +090061#include "VoldUtil.h"
Ken Sumrall29d8da82011-05-18 17:20:07 -070062#include "cryptfs.h"
San Mehat23969932010-01-09 07:08:06 -080063
Jeff Sharkey36801cc2015-03-13 16:09:20 -070064using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060065using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070066
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 Sharkey3ce18252017-10-24 11:08:45 -0600296int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700297 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))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700423 pid_t pid;
424 if (de->d_type != DT_DIR) continue;
425 if (!android::base::ParseInt(de->d_name, &pid)) continue;
426
Jeff Sharkey66270a22015-06-24 11:49:24 -0700427 pidFd = -1;
428 nsFd = -1;
429
430 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
431 if (pidFd < 0) {
432 goto next;
433 }
434 if (fstat(pidFd, &sb) != 0) {
435 PLOG(WARNING) << "Failed to stat " << de->d_name;
436 goto next;
437 }
438 if (sb.st_uid != uid) {
439 goto next;
440 }
441
442 // Matches so far, but refuse to touch if in root namespace
443 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600444 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700445 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
446 goto next;
447 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600448 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700449 LOG(WARNING) << "Skipping due to root namespace";
450 goto next;
451 }
452
453 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600454 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700455 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700456 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700457 goto next;
458 }
459
460 if (!(child = fork())) {
461 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700462 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700463 _exit(1);
464 }
465
Jeff Sharkey3472e522017-10-06 18:02:53 -0600466 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700467
468 std::string storageSource;
469 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700470 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700471 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700472 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700473 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700474 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700475 } else {
476 // Sane default of no storage visible
477 _exit(0);
478 }
479 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900480 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700481 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
482 << de->d_name;
483 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700484 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900485 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
486 MS_REC | MS_SLAVE, NULL)) == -1) {
487 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
488 << de->d_name;
489 _exit(1);
490 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700491
492 // Mount user-specific symlink helper into place
493 userid_t user_id = multiuser_get_user_id(uid);
494 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
495 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
496 NULL, MS_BIND, NULL)) == -1) {
497 PLOG(ERROR) << "Failed to mount " << userSource << " for "
498 << de->d_name;
499 _exit(1);
500 }
501
Jeff Sharkey66270a22015-06-24 11:49:24 -0700502 _exit(0);
503 }
504
505 if (child == -1) {
506 PLOG(ERROR) << "Failed to fork";
507 goto next;
508 } else {
509 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
510 }
511
512next:
513 close(nsFd);
514 close(pidFd);
515 }
516 closedir(dir);
517 return 0;
518}
519
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700520int VolumeManager::reset() {
521 // Tear down all existing disks/volumes and start from a blank slate so
522 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800523 if (mInternalEmulated != nullptr) {
524 mInternalEmulated->destroy();
525 mInternalEmulated->create();
526 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700527 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700528 disk->destroy();
529 disk->create();
530 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600531 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700532 mAddedUsers.clear();
533 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700534 return 0;
535}
536
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700537// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700538int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700539 if (mInternalEmulated == nullptr) {
540 return 0; // already shutdown
541 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700542 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700543 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700544 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700545 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700546 disk->destroy();
547 }
548 mDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700549 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700550 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700551}
552
Jeff Sharkey9c484982015-03-31 10:35:33 -0700553int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700554 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600555 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700556
Jeff Sharkey9c484982015-03-31 10:35:33 -0700557 // First, try gracefully unmounting all known devices
558 if (mInternalEmulated != nullptr) {
559 mInternalEmulated->unmount();
560 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700561 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700562 disk->unmountAll();
563 }
564
565 // Worst case we might have some stale mounts lurking around, so
566 // force unmount those just to be safe.
567 FILE* fp = setmntent("/proc/mounts", "r");
568 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600569 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700570 return -errno;
571 }
572
573 // Some volumes can be stacked on each other, so force unmount in
574 // reverse order to give us the best chance of success.
575 std::list<std::string> toUnmount;
576 mntent* mentry;
577 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600578 auto test = std::string(mentry->mnt_dir);
579 if (android::base::StartsWith(test, "/mnt/")
580 || android::base::StartsWith(test, "/storage/")) {
581 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700582 }
583 }
584 endmntent(fp);
585
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700586 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600587 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700588 android::vold::ForceUnmount(path);
589 }
590
591 return 0;
592}
593
Jeff Sharkey9c484982015-03-31 10:35:33 -0700594extern "C" int vold_unmountAll(void) {
Ken Sumrall425524d2012-06-14 20:55:28 -0700595 VolumeManager *vm = VolumeManager::Instance();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700596 return vm->unmountAll();
Ken Sumrall425524d2012-06-14 20:55:28 -0700597}
598
Jeff Sharkey3472e522017-10-06 18:02:53 -0600599int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700600 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600601 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700602 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600603 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700604 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600605 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700606 return -EINVAL;
607 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700608}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600609
610static size_t kAppFuseMaxMountPointName = 32;
611
612static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
613 if (name.size() > kAppFuseMaxMountPointName) {
614 LOG(ERROR) << "AppFuse mount name is too long.";
615 return -EINVAL;
616 }
617 for (size_t i = 0; i < name.size(); i++) {
618 if (!isalnum(name[i])) {
619 LOG(ERROR) << "AppFuse mount name contains invalid character.";
620 return -EINVAL;
621 }
622 }
623 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
624 return android::OK;
625}
626
627static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
628 // Remove existing mount.
629 android::vold::ForceUnmount(path);
630
631 const auto opts = android::base::StringPrintf(
632 "fd=%i,"
633 "rootmode=40000,"
634 "default_permissions,"
635 "allow_other,"
636 "user_id=%d,group_id=%d,"
637 "context=\"u:object_r:app_fuse_file:s0\","
638 "fscontext=u:object_r:app_fusefs:s0",
639 device_fd,
640 uid,
641 uid);
642
643 const int result = TEMP_FAILURE_RETRY(mount(
644 "/dev/fuse", path.c_str(), "fuse",
645 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
646 if (result != 0) {
647 PLOG(ERROR) << "Failed to mount " << path;
648 return -errno;
649 }
650
651 return android::OK;
652}
653
654static android::status_t runCommandInNamespace(const std::string& command,
655 uid_t uid,
656 pid_t pid,
657 const std::string& path,
658 int device_fd) {
659 if (DEBUG_APPFUSE) {
660 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
661 << " in namespace " << uid;
662 }
663
664 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
665 if (dir.get() == -1) {
666 PLOG(ERROR) << "Failed to open /proc";
667 return -errno;
668 }
669
670 // Obtains process file descriptor.
671 const std::string pid_str = android::base::StringPrintf("%d", pid);
672 const unique_fd pid_fd(
673 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
674 if (pid_fd.get() == -1) {
675 PLOG(ERROR) << "Failed to open /proc/" << pid;
676 return -errno;
677 }
678
679 // Check UID of process.
680 {
681 struct stat sb;
682 const int result = fstat(pid_fd.get(), &sb);
683 if (result == -1) {
684 PLOG(ERROR) << "Failed to stat /proc/" << pid;
685 return -errno;
686 }
687 if (sb.st_uid != AID_SYSTEM) {
688 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
689 << ", actual=" << sb.st_uid;
690 return -EPERM;
691 }
692 }
693
694 // Matches so far, but refuse to touch if in root namespace
695 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600696 std::string rootName;
697 std::string pidName;
698 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
699 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
700 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600701 return -EPERM;
702 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600703 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600704 LOG(ERROR) << "Don't mount appfuse in root namespace";
705 return -EPERM;
706 }
707 }
708
709 // We purposefully leave the namespace open across the fork
710 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
711 if (ns_fd.get() < 0) {
712 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
713 return -errno;
714 }
715
716 int child = fork();
717 if (child == 0) {
718 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
719 PLOG(ERROR) << "Failed to setns";
720 _exit(-errno);
721 }
722
723 if (command == "mount") {
724 _exit(mountInNamespace(uid, device_fd, path));
725 } else if (command == "unmount") {
726 // If it's just after all FD opened on mount point are closed, umount2 can fail with
727 // EBUSY. To avoid the case, specify MNT_DETACH.
728 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
729 errno != EINVAL && errno != ENOENT) {
730 PLOG(ERROR) << "Failed to unmount directory.";
731 _exit(-errno);
732 }
733 if (rmdir(path.c_str()) != 0) {
734 PLOG(ERROR) << "Failed to remove the mount directory.";
735 _exit(-errno);
736 }
737 _exit(android::OK);
738 } else {
739 LOG(ERROR) << "Unknown appfuse command " << command;
740 _exit(-EPERM);
741 }
742 }
743
744 if (child == -1) {
745 PLOG(ERROR) << "Failed to folk child process";
746 return -errno;
747 }
748
749 android::status_t status;
750 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
751
752 return status;
753}
754
755int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
756 int32_t ownerGid, std::string* outVolId) {
757 int id = mNextObbId++;
758
759 auto vol = std::shared_ptr<android::vold::VolumeBase>(
760 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
761 vol->create();
762
763 mObbVolumes.push_back(vol);
764 *outVolId = vol->getId();
765 return android::OK;
766}
767
768int VolumeManager::destroyObb(const std::string& volId) {
769 auto i = mObbVolumes.begin();
770 while (i != mObbVolumes.end()) {
771 if ((*i)->getId() == volId) {
772 (*i)->destroy();
773 i = mObbVolumes.erase(i);
774 } else {
775 ++i;
776 }
777 }
778 return android::OK;
779}
780
781int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
782 android::base::unique_fd* device_fd) {
783 std::string name = std::to_string(mountId);
784
785 // Check mount point name.
786 std::string path;
787 if (getMountPath(uid, name, &path) != android::OK) {
788 LOG(ERROR) << "Invalid mount point name";
789 return -1;
790 }
791
792 // Create directories.
793 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
794 if (result != android::OK) {
795 PLOG(ERROR) << "Failed to prepare directory " << path;
796 return -1;
797 }
798
799 // Open device FD.
800 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
801 if (device_fd->get() == -1) {
802 PLOG(ERROR) << "Failed to open /dev/fuse";
803 return -1;
804 }
805
806 // Mount.
807 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
808}
809
810int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
811 std::string name = std::to_string(mountId);
812
813 // Check mount point name.
814 std::string path;
815 if (getMountPath(uid, name, &path) != android::OK) {
816 LOG(ERROR) << "Invalid mount point name";
817 return -1;
818 }
819
820 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
821}