blob: f367c2a934dcbb5d49f8586f08715a1d4683976d [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
Keun-young Park375ac252017-08-02 17:45:48 -070067bool VolumeManager::shutting_down = false;
68
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060069static const char* kPathUserMount = "/mnt/user";
70static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
71
72static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
73
74/* 512MiB is large enough for testing purposes */
75static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070076
Jeff Sharkey36801cc2015-03-13 16:09:20 -070077static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080078static const unsigned int kMajorBlockExperimentalMin = 240;
79static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070080
San Mehatf1b736b2009-10-10 17:22:08 -070081VolumeManager *VolumeManager::sInstance = NULL;
82
83VolumeManager *VolumeManager::Instance() {
84 if (!sInstance)
85 sInstance = new VolumeManager();
86 return sInstance;
87}
88
89VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080090 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060091 mNextObbId = 0;
San Mehatf1b736b2009-10-10 17:22:08 -070092}
93
94VolumeManager::~VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080095}
96
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060097int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -060098 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -060099 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600100 if (access(kPathVirtualDisk, F_OK) != 0) {
101 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
102 }
103
104 if (mVirtualDisk == nullptr) {
105 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
106 LOG(ERROR) << "Failed to create virtual disk";
107 return -1;
108 }
109
110 struct stat buf;
111 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
112 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
113 return -1;
114 }
115
116 auto disk = new android::vold::Disk("virtual", buf.st_rdev, "virtual",
117 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
118 disk->create();
119 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
120 mDisks.push_back(mVirtualDisk);
121 }
122 } else {
123 if (mVirtualDisk != nullptr) {
124 dev_t device = mVirtualDisk->getDevice();
125
126 auto i = mDisks.begin();
127 while (i != mDisks.end()) {
128 if ((*i)->getDevice() == device) {
129 (*i)->destroy();
130 i = mDisks.erase(i);
131 } else {
132 ++i;
133 }
134 }
135
136 Loop::destroyByDevice(mVirtualDiskPath.c_str());
137 mVirtualDisk = nullptr;
138 }
139
140 if (access(kPathVirtualDisk, F_OK) == 0) {
141 unlink(kPathVirtualDisk);
142 }
143 }
144 return 0;
145}
146
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700147int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800148 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700149 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800150}
151
San Mehatf1b736b2009-10-10 17:22:08 -0700152int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600153 ATRACE_NAME("VolumeManager::start");
154
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700155 // Always start from a clean slate by unmounting everything in
156 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700157 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700158
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600159 Devmapper::destroyAll();
160 Loop::destroyAll();
161
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700162 // Assume that we always have an emulated volume on internal
163 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700164 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700165 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Jeff Sharkey3161fb32015-04-12 16:03:33 -0700166 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700167 mInternalEmulated->create();
168
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600169 // Consider creating a virtual disk
170 updateVirtualDisk();
171
San Mehatf1b736b2009-10-10 17:22:08 -0700172 return 0;
173}
174
175int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700176 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700177 mInternalEmulated->destroy();
178 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700179 return 0;
180}
181
San Mehatfd7f5872009-10-12 11:32:47 -0700182void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700183 std::lock_guard<std::mutex> lock(mLock);
184
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700185 if (mDebug) {
186 LOG(VERBOSE) << "----------------";
187 LOG(VERBOSE) << "handleBlockEvent with action " << (int) evt->getAction();
188 evt->dump();
189 }
San Mehatf1b736b2009-10-10 17:22:08 -0700190
Mateusz Nowak64403792015-08-03 16:39:19 +0200191 std::string eventPath(evt->findParam("DEVPATH")?evt->findParam("DEVPATH"):"");
192 std::string devType(evt->findParam("DEVTYPE")?evt->findParam("DEVTYPE"):"");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700193
194 if (devType != "disk") return;
195
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600196 int major = std::stoi(evt->findParam("MAJOR"));
197 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700198 dev_t device = makedev(major, minor);
199
200 switch (evt->getAction()) {
201 case NetlinkEvent::Action::kAdd: {
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700202 for (const auto& source : mDiskSources) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700203 if (source->matches(eventPath)) {
Yu Ning942d4e82016-01-08 17:36:47 +0800204 // For now, assume that MMC and virtio-blk (the latter is
205 // emulator-specific; see Disk.cpp for details) devices are SD,
206 // and that everything else is USB
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700207 int flags = source->getFlags();
Yu Ning942d4e82016-01-08 17:36:47 +0800208 if (major == kMajorBlockMmc
209 || (android::vold::IsRunningInEmulator()
210 && major >= (int) kMajorBlockExperimentalMin
211 && major <= (int) kMajorBlockExperimentalMax)) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700212 flags |= android::vold::Disk::Flags::kSd;
213 } else {
214 flags |= android::vold::Disk::Flags::kUsb;
215 }
216
217 auto disk = new android::vold::Disk(eventPath, device,
218 source->getNickname(), flags);
219 disk->create();
220 mDisks.push_back(std::shared_ptr<android::vold::Disk>(disk));
221 break;
222 }
223 }
224 break;
225 }
226 case NetlinkEvent::Action::kChange: {
Jeff Sharkey7d9d0112015-04-14 23:14:23 -0700227 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700228 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700229 if (disk->getDevice() == device) {
230 disk->readMetadata();
231 disk->readPartitions();
232 }
233 }
234 break;
235 }
236 case NetlinkEvent::Action::kRemove: {
237 auto i = mDisks.begin();
238 while (i != mDisks.end()) {
239 if ((*i)->getDevice() == device) {
240 (*i)->destroy();
241 i = mDisks.erase(i);
242 } else {
243 ++i;
244 }
245 }
246 break;
247 }
248 default: {
249 LOG(WARNING) << "Unexpected block event action " << (int) evt->getAction();
250 break;
251 }
252 }
253}
254
255void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800256 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700257 mDiskSources.push_back(diskSource);
258}
259
260std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
261 for (auto disk : mDisks) {
262 if (disk->getId() == id) {
263 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700264 }
265 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700266 return nullptr;
267}
San Mehatf1b736b2009-10-10 17:22:08 -0700268
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700269std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800270 // Vold could receive "mount" after "shutdown" command in the extreme case.
271 // If this happens, mInternalEmulated will equal nullptr and
272 // we need to deal with it in order to avoid null pointer crash.
273 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700274 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700275 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700276 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700277 auto vol = disk->findVolume(id);
278 if (vol != nullptr) {
279 return vol;
280 }
281 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600282 for (const auto& vol : mObbVolumes) {
283 if (vol->getId() == id) {
284 return vol;
285 }
286 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700287 return nullptr;
288}
289
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700290void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
291 std::list<std::string>& list) {
292 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700293 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700294 disk->listVolumes(type, list);
295 }
296}
297
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700298int VolumeManager::forgetPartition(const std::string& partGuid) {
299 std::string normalizedGuid;
300 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
301 LOG(WARNING) << "Invalid GUID " << partGuid;
302 return -1;
303 }
304
305 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
306 if (unlink(keyPath.c_str()) != 0) {
307 LOG(ERROR) << "Failed to unlink " << keyPath;
308 return -1;
309 }
310
311 return 0;
312}
313
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700314int VolumeManager::linkPrimary(userid_t userId) {
315 std::string source(mPrimary->getPath());
316 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
317 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700318 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700319 }
320
321 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
322 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
323 if (errno != ENOENT) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600324 PLOG(WARNING) << "Failed to unlink " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700325 }
326 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700327 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700328 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600329 PLOG(WARNING) << "Failed to link";
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700330 return -errno;
331 }
332 return 0;
333}
334
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700335int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
336 mAddedUsers[userId] = userSerialNumber;
337 return 0;
338}
339
340int VolumeManager::onUserRemoved(userid_t userId) {
341 mAddedUsers.erase(userId);
342 return 0;
343}
344
345int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700346 // Note that sometimes the system will spin up processes from Zygote
347 // before actually starting the user, so we're okay if Zygote
348 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600349 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700350 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
351
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700352 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700353 if (mPrimary) {
354 linkPrimary(userId);
355 }
356 return 0;
357}
358
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700359int VolumeManager::onUserStopped(userid_t userId) {
360 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700361 return 0;
362}
363
364int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
365 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700366 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700367 linkPrimary(userId);
368 }
369 return 0;
370}
371
Jeff Sharkey3472e522017-10-06 18:02:53 -0600372static int unmount_tree(const std::string& prefix) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700373 FILE* fp = setmntent("/proc/mounts", "r");
374 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600375 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700376 return -errno;
377 }
378
379 // Some volumes can be stacked on each other, so force unmount in
380 // reverse order to give us the best chance of success.
381 std::list<std::string> toUnmount;
382 mntent* mentry;
383 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600384 auto test = std::string(mentry->mnt_dir) + "/";
385 if (android::base::StartsWith(test, prefix.c_str())) {
386 toUnmount.push_front(test);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700387 }
388 }
389 endmntent(fp);
390
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700391 for (const auto& path : toUnmount) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700392 if (umount2(path.c_str(), MNT_DETACH)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600393 PLOG(ERROR) << "Failed to unmount " << path;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700394 }
395 }
396 return 0;
397}
398
Jeff Sharkey66270a22015-06-24 11:49:24 -0700399int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
400 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
401
402 DIR* dir;
403 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600404 std::string rootName;
405 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700406 int pidFd;
407 int nsFd;
408 struct stat sb;
409 pid_t child;
410
411 if (!(dir = opendir("/proc"))) {
412 PLOG(ERROR) << "Failed to opendir";
413 return -1;
414 }
415
416 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600417 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
418 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700419 closedir(dir);
420 return -1;
421 }
422
423 // Poke through all running PIDs look for apps running as UID
424 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700425 pid_t pid;
426 if (de->d_type != DT_DIR) continue;
427 if (!android::base::ParseInt(de->d_name, &pid)) continue;
428
Jeff Sharkey66270a22015-06-24 11:49:24 -0700429 pidFd = -1;
430 nsFd = -1;
431
432 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
433 if (pidFd < 0) {
434 goto next;
435 }
436 if (fstat(pidFd, &sb) != 0) {
437 PLOG(WARNING) << "Failed to stat " << de->d_name;
438 goto next;
439 }
440 if (sb.st_uid != uid) {
441 goto next;
442 }
443
444 // Matches so far, but refuse to touch if in root namespace
445 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600446 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700447 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
448 goto next;
449 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600450 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700451 LOG(WARNING) << "Skipping due to root namespace";
452 goto next;
453 }
454
455 // We purposefully leave the namespace open across the fork
Jeff Sharkeyfd3dc3c2017-03-27 10:49:21 -0600456 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700457 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700458 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700459 goto next;
460 }
461
462 if (!(child = fork())) {
463 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700464 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700465 _exit(1);
466 }
467
Jeff Sharkey3472e522017-10-06 18:02:53 -0600468 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700469
470 std::string storageSource;
471 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700472 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700473 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700474 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700475 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700476 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700477 } else {
478 // Sane default of no storage visible
479 _exit(0);
480 }
481 if (TEMP_FAILURE_RETRY(mount(storageSource.c_str(), "/storage",
Hidehiko Abe674bed12016-03-09 16:42:10 +0900482 NULL, MS_BIND | MS_REC, NULL)) == -1) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700483 PLOG(ERROR) << "Failed to mount " << storageSource << " for "
484 << de->d_name;
485 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700486 }
Hidehiko Abe674bed12016-03-09 16:42:10 +0900487 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL,
488 MS_REC | MS_SLAVE, NULL)) == -1) {
489 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for "
490 << de->d_name;
491 _exit(1);
492 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700493
494 // Mount user-specific symlink helper into place
495 userid_t user_id = multiuser_get_user_id(uid);
496 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
497 if (TEMP_FAILURE_RETRY(mount(userSource.c_str(), "/storage/self",
498 NULL, MS_BIND, NULL)) == -1) {
499 PLOG(ERROR) << "Failed to mount " << userSource << " for "
500 << de->d_name;
501 _exit(1);
502 }
503
Jeff Sharkey66270a22015-06-24 11:49:24 -0700504 _exit(0);
505 }
506
507 if (child == -1) {
508 PLOG(ERROR) << "Failed to fork";
509 goto next;
510 } else {
511 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
512 }
513
514next:
515 close(nsFd);
516 close(pidFd);
517 }
518 closedir(dir);
519 return 0;
520}
521
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700522int VolumeManager::reset() {
523 // Tear down all existing disks/volumes and start from a blank slate so
524 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800525 if (mInternalEmulated != nullptr) {
526 mInternalEmulated->destroy();
527 mInternalEmulated->create();
528 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700529 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700530 disk->destroy();
531 disk->create();
532 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600533 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700534 mAddedUsers.clear();
535 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700536 return 0;
537}
538
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700539// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700540int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700541 if (mInternalEmulated == nullptr) {
542 return 0; // already shutdown
543 }
Keun-young Park375ac252017-08-02 17:45:48 -0700544 shutting_down = true;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700545 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700546 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700547 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700548 disk->destroy();
549 }
550 mDisks.clear();
Keun-young Park375ac252017-08-02 17:45:48 -0700551 shutting_down = false;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700552 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700553}
554
Jeff Sharkey9c484982015-03-31 10:35:33 -0700555int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700556 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600557 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700558
Jeff Sharkey9c484982015-03-31 10:35:33 -0700559 // First, try gracefully unmounting all known devices
560 if (mInternalEmulated != nullptr) {
561 mInternalEmulated->unmount();
562 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700563 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700564 disk->unmountAll();
565 }
566
567 // Worst case we might have some stale mounts lurking around, so
568 // force unmount those just to be safe.
569 FILE* fp = setmntent("/proc/mounts", "r");
570 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600571 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700572 return -errno;
573 }
574
575 // Some volumes can be stacked on each other, so force unmount in
576 // reverse order to give us the best chance of success.
577 std::list<std::string> toUnmount;
578 mntent* mentry;
579 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600580 auto test = std::string(mentry->mnt_dir);
581 if (android::base::StartsWith(test, "/mnt/")
582 || android::base::StartsWith(test, "/storage/")) {
583 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700584 }
585 }
586 endmntent(fp);
587
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700588 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600589 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700590 android::vold::ForceUnmount(path);
591 }
592
593 return 0;
594}
595
Jeff Sharkey9c484982015-03-31 10:35:33 -0700596extern "C" int vold_unmountAll(void) {
Ken Sumrall425524d2012-06-14 20:55:28 -0700597 VolumeManager *vm = VolumeManager::Instance();
Jeff Sharkey9c484982015-03-31 10:35:33 -0700598 return vm->unmountAll();
Ken Sumrall425524d2012-06-14 20:55:28 -0700599}
600
Jeff Sharkey3472e522017-10-06 18:02:53 -0600601int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700602 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600603 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700604 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600605 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700606 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600607 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700608 return -EINVAL;
609 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700610}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600611
612static size_t kAppFuseMaxMountPointName = 32;
613
614static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
615 if (name.size() > kAppFuseMaxMountPointName) {
616 LOG(ERROR) << "AppFuse mount name is too long.";
617 return -EINVAL;
618 }
619 for (size_t i = 0; i < name.size(); i++) {
620 if (!isalnum(name[i])) {
621 LOG(ERROR) << "AppFuse mount name contains invalid character.";
622 return -EINVAL;
623 }
624 }
625 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
626 return android::OK;
627}
628
629static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
630 // Remove existing mount.
631 android::vold::ForceUnmount(path);
632
633 const auto opts = android::base::StringPrintf(
634 "fd=%i,"
635 "rootmode=40000,"
636 "default_permissions,"
637 "allow_other,"
638 "user_id=%d,group_id=%d,"
639 "context=\"u:object_r:app_fuse_file:s0\","
640 "fscontext=u:object_r:app_fusefs:s0",
641 device_fd,
642 uid,
643 uid);
644
645 const int result = TEMP_FAILURE_RETRY(mount(
646 "/dev/fuse", path.c_str(), "fuse",
647 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
648 if (result != 0) {
649 PLOG(ERROR) << "Failed to mount " << path;
650 return -errno;
651 }
652
653 return android::OK;
654}
655
656static android::status_t runCommandInNamespace(const std::string& command,
657 uid_t uid,
658 pid_t pid,
659 const std::string& path,
660 int device_fd) {
661 if (DEBUG_APPFUSE) {
662 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
663 << " in namespace " << uid;
664 }
665
666 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
667 if (dir.get() == -1) {
668 PLOG(ERROR) << "Failed to open /proc";
669 return -errno;
670 }
671
672 // Obtains process file descriptor.
673 const std::string pid_str = android::base::StringPrintf("%d", pid);
674 const unique_fd pid_fd(
675 openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
676 if (pid_fd.get() == -1) {
677 PLOG(ERROR) << "Failed to open /proc/" << pid;
678 return -errno;
679 }
680
681 // Check UID of process.
682 {
683 struct stat sb;
684 const int result = fstat(pid_fd.get(), &sb);
685 if (result == -1) {
686 PLOG(ERROR) << "Failed to stat /proc/" << pid;
687 return -errno;
688 }
689 if (sb.st_uid != AID_SYSTEM) {
690 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
691 << ", actual=" << sb.st_uid;
692 return -EPERM;
693 }
694 }
695
696 // Matches so far, but refuse to touch if in root namespace
697 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600698 std::string rootName;
699 std::string pidName;
700 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName)
701 || !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
702 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600703 return -EPERM;
704 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600705 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600706 LOG(ERROR) << "Don't mount appfuse in root namespace";
707 return -EPERM;
708 }
709 }
710
711 // We purposefully leave the namespace open across the fork
712 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
713 if (ns_fd.get() < 0) {
714 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
715 return -errno;
716 }
717
718 int child = fork();
719 if (child == 0) {
720 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
721 PLOG(ERROR) << "Failed to setns";
722 _exit(-errno);
723 }
724
725 if (command == "mount") {
726 _exit(mountInNamespace(uid, device_fd, path));
727 } else if (command == "unmount") {
728 // If it's just after all FD opened on mount point are closed, umount2 can fail with
729 // EBUSY. To avoid the case, specify MNT_DETACH.
730 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 &&
731 errno != EINVAL && errno != ENOENT) {
732 PLOG(ERROR) << "Failed to unmount directory.";
733 _exit(-errno);
734 }
735 if (rmdir(path.c_str()) != 0) {
736 PLOG(ERROR) << "Failed to remove the mount directory.";
737 _exit(-errno);
738 }
739 _exit(android::OK);
740 } else {
741 LOG(ERROR) << "Unknown appfuse command " << command;
742 _exit(-EPERM);
743 }
744 }
745
746 if (child == -1) {
747 PLOG(ERROR) << "Failed to folk child process";
748 return -errno;
749 }
750
751 android::status_t status;
752 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
753
754 return status;
755}
756
757int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
758 int32_t ownerGid, std::string* outVolId) {
759 int id = mNextObbId++;
760
761 auto vol = std::shared_ptr<android::vold::VolumeBase>(
762 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
763 vol->create();
764
765 mObbVolumes.push_back(vol);
766 *outVolId = vol->getId();
767 return android::OK;
768}
769
770int VolumeManager::destroyObb(const std::string& volId) {
771 auto i = mObbVolumes.begin();
772 while (i != mObbVolumes.end()) {
773 if ((*i)->getId() == volId) {
774 (*i)->destroy();
775 i = mObbVolumes.erase(i);
776 } else {
777 ++i;
778 }
779 }
780 return android::OK;
781}
782
783int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
784 android::base::unique_fd* device_fd) {
785 std::string name = std::to_string(mountId);
786
787 // Check mount point name.
788 std::string path;
789 if (getMountPath(uid, name, &path) != android::OK) {
790 LOG(ERROR) << "Invalid mount point name";
791 return -1;
792 }
793
794 // Create directories.
795 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
796 if (result != android::OK) {
797 PLOG(ERROR) << "Failed to prepare directory " << path;
798 return -1;
799 }
800
801 // Open device FD.
802 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
803 if (device_fd->get() == -1) {
804 PLOG(ERROR) << "Failed to open /dev/fuse";
805 return -1;
806 }
807
808 // Mount.
809 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
810}
811
812int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
813 std::string name = std::to_string(mountId);
814
815 // Check mount point name.
816 std::string path;
817 if (getMountPath(uid, name, &path) != android::OK) {
818 LOG(ERROR) << "Invalid mount point name";
819 return -1;
820 }
821
822 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
823}