blob: 75e28d483f767e9eee7572ef1954640f09de77c8 [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>
Elliott Hughes0e08e842017-05-18 09:08:24 -070029#include <sys/sysmacros.h>
Paul Crowley8915d622018-09-18 15:14:18 -070030#include <sys/types.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
Paul Crowleyc6433a22017-10-24 14:54:43 -070051#include <ext4_utils/ext4_crypt.h>
52
53#include "Devmapper.h"
54#include "Ext4Crypt.h"
San Mehata19b2502010-01-06 10:33:53 -080055#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070056#include "NetlinkManager.h"
57#include "Process.h"
58#include "Utils.h"
59#include "VoldUtil.h"
60#include "VolumeManager.h"
61#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070062#include "fs/Ext4.h"
63#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070064#include "model/EmulatedVolume.h"
65#include "model/ObbVolume.h"
San Mehat23969932010-01-09 07:08:06 -080066
Mark Salyzync4405e92018-09-20 10:09:27 -070067using android::base::StartsWith;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070068using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060069using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070070
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060071static const char* kPathUserMount = "/mnt/user";
72static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
73
74static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
75
76/* 512MiB is large enough for testing purposes */
77static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070078
Jeff Sharkey36801cc2015-03-13 16:09:20 -070079static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080080static const unsigned int kMajorBlockExperimentalMin = 240;
81static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070082
Paul Crowley8915d622018-09-18 15:14:18 -070083VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070084
Paul Crowley8915d622018-09-18 15:14:18 -070085VolumeManager* VolumeManager::Instance() {
86 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070087 return sInstance;
88}
89
90VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080091 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060092 mNextObbId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -070093 // For security reasons, assume that a secure keyguard is
94 // showing until we hear otherwise
95 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -070096}
97
Paul Crowley8915d622018-09-18 15:14:18 -070098VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -080099
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600100int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600101 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600102 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600103 if (access(kPathVirtualDisk, F_OK) != 0) {
104 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
105 }
106
107 if (mVirtualDisk == nullptr) {
108 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
109 LOG(ERROR) << "Failed to create virtual disk";
110 return -1;
111 }
112
113 struct stat buf;
114 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
115 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
116 return -1;
117 }
118
Paul Crowley8915d622018-09-18 15:14:18 -0700119 auto disk = new android::vold::Disk(
120 "virtual", buf.st_rdev, "virtual",
121 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600122 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700123 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600124 }
125 } else {
126 if (mVirtualDisk != nullptr) {
127 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700128 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129
130 Loop::destroyByDevice(mVirtualDiskPath.c_str());
131 mVirtualDisk = nullptr;
132 }
133
134 if (access(kPathVirtualDisk, F_OK) == 0) {
135 unlink(kPathVirtualDisk);
136 }
137 }
138 return 0;
139}
140
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700141int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800142 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700143 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800144}
145
San Mehatf1b736b2009-10-10 17:22:08 -0700146int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600147 ATRACE_NAME("VolumeManager::start");
148
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700149 // Always start from a clean slate by unmounting everything in
150 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700151 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700152
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600153 Devmapper::destroyAll();
154 Loop::destroyAll();
155
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700156 // Assume that we always have an emulated volume on internal
157 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700158 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700159 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowley8915d622018-09-18 15:14:18 -0700160 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700161 mInternalEmulated->create();
162
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600163 // Consider creating a virtual disk
164 updateVirtualDisk();
165
San Mehatf1b736b2009-10-10 17:22:08 -0700166 return 0;
167}
168
169int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700170 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700171 mInternalEmulated->destroy();
172 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700173 return 0;
174}
175
Paul Crowley8915d622018-09-18 15:14:18 -0700176void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700177 std::lock_guard<std::mutex> lock(mLock);
178
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700179 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700180 LOG(DEBUG) << "----------------";
181 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700182 evt->dump();
183 }
San Mehatf1b736b2009-10-10 17:22:08 -0700184
Paul Crowley8915d622018-09-18 15:14:18 -0700185 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
186 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700187
188 if (devType != "disk") return;
189
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600190 int major = std::stoi(evt->findParam("MAJOR"));
191 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192 dev_t device = makedev(major, minor);
193
194 switch (evt->getAction()) {
Paul Crowley8915d622018-09-18 15:14:18 -0700195 case NetlinkEvent::Action::kAdd: {
196 for (const auto& source : mDiskSources) {
197 if (source->matches(eventPath)) {
198 // For now, assume that MMC and virtio-blk (the latter is
199 // emulator-specific; see Disk.cpp for details) devices are SD,
200 // and that everything else is USB
201 int flags = source->getFlags();
202 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
203 major >= (int)kMajorBlockExperimentalMin &&
204 major <= (int)kMajorBlockExperimentalMax)) {
205 flags |= android::vold::Disk::Flags::kSd;
206 } else {
207 flags |= android::vold::Disk::Flags::kUsb;
208 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700209
Paul Crowley8915d622018-09-18 15:14:18 -0700210 auto disk =
211 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
212 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
213 break;
214 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700215 }
Paul Crowley8915d622018-09-18 15:14:18 -0700216 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700217 }
Paul Crowley8915d622018-09-18 15:14:18 -0700218 case NetlinkEvent::Action::kChange: {
219 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
220 handleDiskChanged(device);
221 break;
222 }
223 case NetlinkEvent::Action::kRemove: {
224 handleDiskRemoved(device);
225 break;
226 }
227 default: {
228 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
229 break;
230 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700231 }
232}
233
Jeff Sharkey401b2602017-12-14 22:15:20 -0700234void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
235 // For security reasons, if secure keyguard is showing, wait
236 // until the user unlocks the device to actually touch it
237 if (mSecureKeyguardShowing) {
238 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowley8915d622018-09-18 15:14:18 -0700239 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700240 mPendingDisks.push_back(disk);
241 } else {
242 disk->create();
243 mDisks.push_back(disk);
244 }
245}
246
247void VolumeManager::handleDiskChanged(dev_t device) {
248 for (const auto& disk : mDisks) {
249 if (disk->getDevice() == device) {
250 disk->readMetadata();
251 disk->readPartitions();
252 }
253 }
254
255 // For security reasons, we ignore all pending disks, since
256 // we'll scan them once the device is unlocked
257}
258
259void VolumeManager::handleDiskRemoved(dev_t device) {
260 auto i = mDisks.begin();
261 while (i != mDisks.end()) {
262 if ((*i)->getDevice() == device) {
263 (*i)->destroy();
264 i = mDisks.erase(i);
265 } else {
266 ++i;
267 }
268 }
269 auto j = mPendingDisks.begin();
270 while (j != mPendingDisks.end()) {
271 if ((*j)->getDevice() == device) {
272 j = mPendingDisks.erase(j);
273 } else {
274 ++j;
275 }
276 }
277}
278
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700279void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800280 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700281 mDiskSources.push_back(diskSource);
282}
283
284std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
285 for (auto disk : mDisks) {
286 if (disk->getId() == id) {
287 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700288 }
289 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700290 return nullptr;
291}
San Mehatf1b736b2009-10-10 17:22:08 -0700292
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700293std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800294 // Vold could receive "mount" after "shutdown" command in the extreme case.
295 // If this happens, mInternalEmulated will equal nullptr and
296 // we need to deal with it in order to avoid null pointer crash.
297 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700298 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700299 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700300 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700301 auto vol = disk->findVolume(id);
302 if (vol != nullptr) {
303 return vol;
304 }
305 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600306 for (const auto& vol : mObbVolumes) {
307 if (vol->getId() == id) {
308 return vol;
309 }
310 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700311 return nullptr;
312}
313
Paul Crowley8915d622018-09-18 15:14:18 -0700314void VolumeManager::listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700315 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700316 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700317 disk->listVolumes(type, list);
318 }
319}
320
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600321int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700322 std::string normalizedGuid;
323 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
324 LOG(WARNING) << "Invalid GUID " << partGuid;
325 return -1;
326 }
327
Paul Crowleyc6433a22017-10-24 14:54:43 -0700328 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700329 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
330 if (unlink(keyPath.c_str()) != 0) {
331 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700332 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700333 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700334 if (e4crypt_is_native()) {
335 if (!e4crypt_destroy_volume_keys(fsUuid)) {
336 success = false;
337 }
338 }
339 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700340}
341
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700342int VolumeManager::linkPrimary(userid_t userId) {
343 std::string source(mPrimary->getPath());
344 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
345 source = StringPrintf("%s/%d", source.c_str(), userId);
Jeff Sharkey32679a82015-07-21 14:22:01 -0700346 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700347 }
348
349 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
350 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
351 if (errno != ENOENT) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600352 PLOG(WARNING) << "Failed to unlink " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700353 }
354 }
Jeff Sharkey1bfb3752015-04-29 15:22:23 -0700355 LOG(DEBUG) << "Linking " << source << " to " << target;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700356 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600357 PLOG(WARNING) << "Failed to link";
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700358 return -errno;
359 }
360 return 0;
361}
362
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700363int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
364 mAddedUsers[userId] = userSerialNumber;
365 return 0;
366}
367
368int VolumeManager::onUserRemoved(userid_t userId) {
369 mAddedUsers.erase(userId);
370 return 0;
371}
372
373int VolumeManager::onUserStarted(userid_t userId) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700374 // Note that sometimes the system will spin up processes from Zygote
375 // before actually starting the user, so we're okay if Zygote
376 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600377 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700378 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
379
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700380 mStartedUsers.insert(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700381 if (mPrimary) {
382 linkPrimary(userId);
383 }
384 return 0;
385}
386
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700387int VolumeManager::onUserStopped(userid_t userId) {
388 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700389 return 0;
390}
391
Jeff Sharkey401b2602017-12-14 22:15:20 -0700392int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
393 mSecureKeyguardShowing = isShowing;
394 if (!mSecureKeyguardShowing) {
395 // Now that secure keyguard has been dismissed, process
396 // any pending disks
397 for (const auto& disk : mPendingDisks) {
398 disk->create();
399 mDisks.push_back(disk);
400 }
401 mPendingDisks.clear();
402 }
403 return 0;
404}
405
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700406int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
407 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700408 for (userid_t userId : mStartedUsers) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700409 linkPrimary(userId);
410 }
411 return 0;
412}
413
Jeff Sharkey66270a22015-06-24 11:49:24 -0700414int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
415 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
416
417 DIR* dir;
418 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600419 std::string rootName;
420 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700421 int pidFd;
422 int nsFd;
423 struct stat sb;
424 pid_t child;
425
426 if (!(dir = opendir("/proc"))) {
427 PLOG(ERROR) << "Failed to opendir";
428 return -1;
429 }
430
431 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600432 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
433 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700434 closedir(dir);
435 return -1;
436 }
437
438 // Poke through all running PIDs look for apps running as UID
439 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700440 pid_t pid;
441 if (de->d_type != DT_DIR) continue;
442 if (!android::base::ParseInt(de->d_name, &pid)) continue;
443
Jeff Sharkey66270a22015-06-24 11:49:24 -0700444 pidFd = -1;
445 nsFd = -1;
446
447 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
448 if (pidFd < 0) {
449 goto next;
450 }
451 if (fstat(pidFd, &sb) != 0) {
452 PLOG(WARNING) << "Failed to stat " << de->d_name;
453 goto next;
454 }
455 if (sb.st_uid != uid) {
456 goto next;
457 }
458
459 // Matches so far, but refuse to touch if in root namespace
460 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600461 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700462 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
463 goto next;
464 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600465 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700466 LOG(WARNING) << "Skipping due to root namespace";
467 goto next;
468 }
469
470 // We purposefully leave the namespace open across the fork
Paul Crowley8915d622018-09-18 15:14:18 -0700471 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700472 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700473 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700474 goto next;
475 }
476
477 if (!(child = fork())) {
478 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700479 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700480 _exit(1);
481 }
482
Sudheer Shanka99d304a2018-09-27 14:53:51 -0700483 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700484
485 std::string storageSource;
486 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700487 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700488 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700489 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700490 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700491 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700492 } else {
493 // Sane default of no storage visible
494 _exit(0);
495 }
Paul Crowley8915d622018-09-18 15:14:18 -0700496 if (TEMP_FAILURE_RETRY(
497 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
498 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700499 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700500 }
Paul Crowley8915d622018-09-18 15:14:18 -0700501 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
502 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +0900503 _exit(1);
504 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700505
506 // Mount user-specific symlink helper into place
507 userid_t user_id = multiuser_get_user_id(uid);
508 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowley8915d622018-09-18 15:14:18 -0700509 if (TEMP_FAILURE_RETRY(
510 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
511 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700512 _exit(1);
513 }
514
Jeff Sharkey66270a22015-06-24 11:49:24 -0700515 _exit(0);
516 }
517
518 if (child == -1) {
519 PLOG(ERROR) << "Failed to fork";
520 goto next;
521 } else {
522 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
523 }
524
Paul Crowley8915d622018-09-18 15:14:18 -0700525 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700526 close(nsFd);
527 close(pidFd);
528 }
529 closedir(dir);
530 return 0;
531}
532
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700533int VolumeManager::reset() {
534 // Tear down all existing disks/volumes and start from a blank slate so
535 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800536 if (mInternalEmulated != nullptr) {
537 mInternalEmulated->destroy();
538 mInternalEmulated->create();
539 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700540 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700541 disk->destroy();
542 disk->create();
543 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600544 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700545 mAddedUsers.clear();
546 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700547 return 0;
548}
549
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700550// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700551int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700552 if (mInternalEmulated == nullptr) {
Paul Crowley8915d622018-09-18 15:14:18 -0700553 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700554 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700555 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700556 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700557 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700558 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700559 disk->destroy();
560 }
561 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700562 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700563 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700564 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700565}
566
Jeff Sharkey9c484982015-03-31 10:35:33 -0700567int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700568 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600569 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700570
Jeff Sharkey9c484982015-03-31 10:35:33 -0700571 // First, try gracefully unmounting all known devices
572 if (mInternalEmulated != nullptr) {
573 mInternalEmulated->unmount();
574 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700575 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700576 disk->unmountAll();
577 }
578
579 // Worst case we might have some stale mounts lurking around, so
580 // force unmount those just to be safe.
581 FILE* fp = setmntent("/proc/mounts", "r");
582 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600583 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700584 return -errno;
585 }
586
587 // Some volumes can be stacked on each other, so force unmount in
588 // reverse order to give us the best chance of success.
589 std::list<std::string> toUnmount;
590 mntent* mentry;
591 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600592 auto test = std::string(mentry->mnt_dir);
Mark Salyzync4405e92018-09-20 10:09:27 -0700593 if ((StartsWith(test, "/mnt/") &&
594#ifdef __ANDROID_DEBUGGABLE__
595 !StartsWith(test, "/mnt/scratch") &&
596#endif
597 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
598 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600599 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700600 }
601 }
602 endmntent(fp);
603
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700604 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600605 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700606 android::vold::ForceUnmount(path);
607 }
608
609 return 0;
610}
611
Jeff Sharkey3472e522017-10-06 18:02:53 -0600612int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700613 // Only offer to create directories for paths managed by vold
Mark Salyzync4405e92018-09-20 10:09:27 -0700614 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700615 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600616 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700617 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600618 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700619 return -EINVAL;
620 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700621}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600622
623static size_t kAppFuseMaxMountPointName = 32;
624
625static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
626 if (name.size() > kAppFuseMaxMountPointName) {
627 LOG(ERROR) << "AppFuse mount name is too long.";
628 return -EINVAL;
629 }
630 for (size_t i = 0; i < name.size(); i++) {
631 if (!isalnum(name[i])) {
632 LOG(ERROR) << "AppFuse mount name contains invalid character.";
633 return -EINVAL;
634 }
635 }
Mark Salyzync4405e92018-09-20 10:09:27 -0700636 *path = StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600637 return android::OK;
638}
639
640static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
641 // Remove existing mount.
642 android::vold::ForceUnmount(path);
643
Mark Salyzync4405e92018-09-20 10:09:27 -0700644 const auto opts = StringPrintf(
Paul Crowley8915d622018-09-18 15:14:18 -0700645 "fd=%i,"
646 "rootmode=40000,"
647 "default_permissions,"
648 "allow_other,"
649 "user_id=%d,group_id=%d,"
650 "context=\"u:object_r:app_fuse_file:s0\","
651 "fscontext=u:object_r:app_fusefs:s0",
652 device_fd, uid, uid);
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600653
Paul Crowley8915d622018-09-18 15:14:18 -0700654 const int result =
655 TEMP_FAILURE_RETRY(mount("/dev/fuse", path.c_str(), "fuse",
656 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600657 if (result != 0) {
658 PLOG(ERROR) << "Failed to mount " << path;
659 return -errno;
660 }
661
662 return android::OK;
663}
664
Paul Crowley8915d622018-09-18 15:14:18 -0700665static android::status_t runCommandInNamespace(const std::string& command, uid_t uid, pid_t pid,
666 const std::string& path, int device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600667 if (DEBUG_APPFUSE) {
668 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
669 << " in namespace " << uid;
670 }
671
672 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
673 if (dir.get() == -1) {
674 PLOG(ERROR) << "Failed to open /proc";
675 return -errno;
676 }
677
678 // Obtains process file descriptor.
Mark Salyzync4405e92018-09-20 10:09:27 -0700679 const std::string pid_str = StringPrintf("%d", pid);
Paul Crowley8915d622018-09-18 15:14:18 -0700680 const unique_fd pid_fd(openat(dir.get(), pid_str.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600681 if (pid_fd.get() == -1) {
682 PLOG(ERROR) << "Failed to open /proc/" << pid;
683 return -errno;
684 }
685
686 // Check UID of process.
687 {
688 struct stat sb;
689 const int result = fstat(pid_fd.get(), &sb);
690 if (result == -1) {
691 PLOG(ERROR) << "Failed to stat /proc/" << pid;
692 return -errno;
693 }
694 if (sb.st_uid != AID_SYSTEM) {
695 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
Paul Crowley8915d622018-09-18 15:14:18 -0700696 << ", actual=" << sb.st_uid;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600697 return -EPERM;
698 }
699 }
700
701 // Matches so far, but refuse to touch if in root namespace
702 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600703 std::string rootName;
704 std::string pidName;
Paul Crowley8915d622018-09-18 15:14:18 -0700705 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName) ||
706 !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600707 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600708 return -EPERM;
709 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600710 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600711 LOG(ERROR) << "Don't mount appfuse in root namespace";
712 return -EPERM;
713 }
714 }
715
716 // We purposefully leave the namespace open across the fork
Paul Crowley8915d622018-09-18 15:14:18 -0700717 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600718 if (ns_fd.get() < 0) {
719 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
720 return -errno;
721 }
722
723 int child = fork();
724 if (child == 0) {
725 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
726 PLOG(ERROR) << "Failed to setns";
727 _exit(-errno);
728 }
729
730 if (command == "mount") {
731 _exit(mountInNamespace(uid, device_fd, path));
732 } else if (command == "unmount") {
733 // If it's just after all FD opened on mount point are closed, umount2 can fail with
734 // EBUSY. To avoid the case, specify MNT_DETACH.
Paul Crowley8915d622018-09-18 15:14:18 -0700735 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 && errno != EINVAL &&
736 errno != ENOENT) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600737 PLOG(ERROR) << "Failed to unmount directory.";
738 _exit(-errno);
739 }
740 if (rmdir(path.c_str()) != 0) {
741 PLOG(ERROR) << "Failed to remove the mount directory.";
742 _exit(-errno);
743 }
744 _exit(android::OK);
745 } else {
746 LOG(ERROR) << "Unknown appfuse command " << command;
747 _exit(-EPERM);
748 }
749 }
750
751 if (child == -1) {
752 PLOG(ERROR) << "Failed to folk child process";
753 return -errno;
754 }
755
756 android::status_t status;
757 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
758
759 return status;
760}
761
762int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowley8915d622018-09-18 15:14:18 -0700763 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600764 int id = mNextObbId++;
765
766 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowley8915d622018-09-18 15:14:18 -0700767 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600768 vol->create();
769
770 mObbVolumes.push_back(vol);
771 *outVolId = vol->getId();
772 return android::OK;
773}
774
775int VolumeManager::destroyObb(const std::string& volId) {
776 auto i = mObbVolumes.begin();
777 while (i != mObbVolumes.end()) {
778 if ((*i)->getId() == volId) {
779 (*i)->destroy();
780 i = mObbVolumes.erase(i);
781 } else {
782 ++i;
783 }
784 }
785 return android::OK;
786}
787
Mark Salyzync4405e92018-09-20 10:09:27 -0700788int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId, unique_fd* device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600789 std::string name = std::to_string(mountId);
790
791 // Check mount point name.
792 std::string path;
793 if (getMountPath(uid, name, &path) != android::OK) {
794 LOG(ERROR) << "Invalid mount point name";
795 return -1;
796 }
797
798 // Create directories.
799 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
800 if (result != android::OK) {
801 PLOG(ERROR) << "Failed to prepare directory " << path;
802 return -1;
803 }
804
805 // Open device FD.
Paul Crowley8915d622018-09-18 15:14:18 -0700806 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600807 if (device_fd->get() == -1) {
808 PLOG(ERROR) << "Failed to open /dev/fuse";
809 return -1;
810 }
811
812 // Mount.
813 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
814}
815
816int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
817 std::string name = std::to_string(mountId);
818
819 // Check mount point name.
820 std::string path;
821 if (getMountPath(uid, name, &path) != android::OK) {
822 LOG(ERROR) << "Invalid mount point name";
823 return -1;
824 }
825
826 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
827}