blob: 767da9e2ebc1a1ea22456020caabf771aee03027 [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 Crowleyedf7a4e2018-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
Sudheer Shanka53947a32018-08-01 10:24:13 -070067using android::base::GetBoolProperty;
68using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070069using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060070using android::base::unique_fd;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070071
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060072static const char* kPathUserMount = "/mnt/user";
73static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
74
Sudheer Shanka53947a32018-08-01 10:24:13 -070075static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060076static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
77
Sudheer Shanka53947a32018-08-01 10:24:13 -070078static const std::string kEmptyString("");
79
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060080/* 512MiB is large enough for testing purposes */
81static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070082
Jeff Sharkey36801cc2015-03-13 16:09:20 -070083static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +080084static const unsigned int kMajorBlockExperimentalMin = 240;
85static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070086
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070087VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -070088
Paul Crowleyedf7a4e2018-09-18 15:14:18 -070089VolumeManager* VolumeManager::Instance() {
90 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -070091 return sInstance;
92}
93
94VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -080095 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060096 mNextObbId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -070097 // For security reasons, assume that a secure keyguard is
98 // showing until we hear otherwise
99 mSecureKeyguardShowing = true;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700100 mMntStorageCreated = false;
San Mehatf1b736b2009-10-10 17:22:08 -0700101}
102
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700103VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800104
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600105int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600106 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Jeff Sharkey3472e522017-10-06 18:02:53 -0600107 if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600108 if (access(kPathVirtualDisk, F_OK) != 0) {
109 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
110 }
111
112 if (mVirtualDisk == nullptr) {
113 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
114 LOG(ERROR) << "Failed to create virtual disk";
115 return -1;
116 }
117
118 struct stat buf;
119 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
120 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
121 return -1;
122 }
123
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700124 auto disk = new android::vold::Disk(
125 "virtual", buf.st_rdev, "virtual",
126 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600127 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700128 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129 }
130 } else {
131 if (mVirtualDisk != nullptr) {
132 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700133 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600134
135 Loop::destroyByDevice(mVirtualDiskPath.c_str());
136 mVirtualDisk = nullptr;
137 }
138
139 if (access(kPathVirtualDisk, F_OK) == 0) {
140 unlink(kPathVirtualDisk);
141 }
142 }
143 return 0;
144}
145
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700146int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800147 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700148 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800149}
150
San Mehatf1b736b2009-10-10 17:22:08 -0700151int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600152 ATRACE_NAME("VolumeManager::start");
153
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700154 // Always start from a clean slate by unmounting everything in
155 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700156 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700157
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600158 Devmapper::destroyAll();
159 Loop::destroyAll();
160
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700161 // Assume that we always have an emulated volume on internal
162 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700163 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700164 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700165 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700166 mInternalEmulated->create();
167
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600168 // Consider creating a virtual disk
169 updateVirtualDisk();
170
San Mehatf1b736b2009-10-10 17:22:08 -0700171 return 0;
172}
173
174int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700175 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700176 mInternalEmulated->destroy();
177 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700178 return 0;
179}
180
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700181void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700182 std::lock_guard<std::mutex> lock(mLock);
183
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700184 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700185 LOG(DEBUG) << "----------------";
186 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700187 evt->dump();
188 }
San Mehatf1b736b2009-10-10 17:22:08 -0700189
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700190 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
191 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700192
193 if (devType != "disk") return;
194
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600195 int major = std::stoi(evt->findParam("MAJOR"));
196 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700197 dev_t device = makedev(major, minor);
198
199 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700200 case NetlinkEvent::Action::kAdd: {
201 for (const auto& source : mDiskSources) {
202 if (source->matches(eventPath)) {
203 // For now, assume that MMC and virtio-blk (the latter is
204 // emulator-specific; see Disk.cpp for details) devices are SD,
205 // and that everything else is USB
206 int flags = source->getFlags();
207 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
208 major >= (int)kMajorBlockExperimentalMin &&
209 major <= (int)kMajorBlockExperimentalMax)) {
210 flags |= android::vold::Disk::Flags::kSd;
211 } else {
212 flags |= android::vold::Disk::Flags::kUsb;
213 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700214
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700215 auto disk =
216 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
217 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
218 break;
219 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700220 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700221 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700222 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700223 case NetlinkEvent::Action::kChange: {
224 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
225 handleDiskChanged(device);
226 break;
227 }
228 case NetlinkEvent::Action::kRemove: {
229 handleDiskRemoved(device);
230 break;
231 }
232 default: {
233 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
234 break;
235 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700236 }
237}
238
Jeff Sharkey401b2602017-12-14 22:15:20 -0700239void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
240 // For security reasons, if secure keyguard is showing, wait
241 // until the user unlocks the device to actually touch it
242 if (mSecureKeyguardShowing) {
243 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700244 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700245 mPendingDisks.push_back(disk);
246 } else {
247 disk->create();
248 mDisks.push_back(disk);
249 }
250}
251
252void VolumeManager::handleDiskChanged(dev_t device) {
253 for (const auto& disk : mDisks) {
254 if (disk->getDevice() == device) {
255 disk->readMetadata();
256 disk->readPartitions();
257 }
258 }
259
260 // For security reasons, we ignore all pending disks, since
261 // we'll scan them once the device is unlocked
262}
263
264void VolumeManager::handleDiskRemoved(dev_t device) {
265 auto i = mDisks.begin();
266 while (i != mDisks.end()) {
267 if ((*i)->getDevice() == device) {
268 (*i)->destroy();
269 i = mDisks.erase(i);
270 } else {
271 ++i;
272 }
273 }
274 auto j = mPendingDisks.begin();
275 while (j != mPendingDisks.end()) {
276 if ((*j)->getDevice() == device) {
277 j = mPendingDisks.erase(j);
278 } else {
279 ++j;
280 }
281 }
282}
283
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700284void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800285 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700286 mDiskSources.push_back(diskSource);
287}
288
289std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
290 for (auto disk : mDisks) {
291 if (disk->getId() == id) {
292 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700293 }
294 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700295 return nullptr;
296}
San Mehatf1b736b2009-10-10 17:22:08 -0700297
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700298std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800299 // Vold could receive "mount" after "shutdown" command in the extreme case.
300 // If this happens, mInternalEmulated will equal nullptr and
301 // we need to deal with it in order to avoid null pointer crash.
302 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700303 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700304 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700305 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700306 auto vol = disk->findVolume(id);
307 if (vol != nullptr) {
308 return vol;
309 }
310 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600311 for (const auto& vol : mObbVolumes) {
312 if (vol->getId() == id) {
313 return vol;
314 }
315 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700316 return nullptr;
317}
318
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700319void VolumeManager::listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700320 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700321 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700322 disk->listVolumes(type, list);
323 }
324}
325
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600326int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700327 std::string normalizedGuid;
328 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
329 LOG(WARNING) << "Invalid GUID " << partGuid;
330 return -1;
331 }
332
Paul Crowleyc6433a22017-10-24 14:54:43 -0700333 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700334 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
335 if (unlink(keyPath.c_str()) != 0) {
336 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700337 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700338 }
Paul Crowleyc6433a22017-10-24 14:54:43 -0700339 if (e4crypt_is_native()) {
340 if (!e4crypt_destroy_volume_keys(fsUuid)) {
341 success = false;
342 }
343 }
344 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700345}
346
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700347static int prepareMntStorageDir() {
348 std::string mntTarget("/mnt/storage");
349 if (fs_prepare_dir(mntTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
350 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTarget;
351 return -errno;
352 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700353 if (TEMP_FAILURE_RETRY(mount("/mnt/runtime/write", mntTarget.c_str(), nullptr, MS_BIND | MS_REC,
354 nullptr)) == -1) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700355 PLOG(ERROR) << "Failed to mount /mnt/runtime/write at " << mntTarget;
356 return -errno;
357 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700358 if (TEMP_FAILURE_RETRY(
359 mount(nullptr, mntTarget.c_str(), nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700360 PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTarget;
361 return -errno;
362 }
363 return 0;
364}
365
Sudheer Shanka53947a32018-08-01 10:24:13 -0700366int VolumeManager::linkPrimary(userid_t userId, const std::vector<std::string>& packageNames) {
367 if (GetBoolProperty(kIsolatedStorage, false)) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700368 // This should ideally go into start() but it's possible that system properties are not
369 // loaded at that point.
370 if (!mMntStorageCreated) {
371 prepareMntStorageDir();
372 mMntStorageCreated = true;
373 }
374
Sudheer Shankac7562092018-08-24 10:20:56 -0700375 if (mountSandboxesForPrimaryVol(userId, packageNames) != 0) {
Sudheer Shankaa695f252018-08-03 18:07:52 -0700376 return -errno;
377 }
378 // Keep /sdcard working for shell process
379 std::string primarySource(mPrimary->getPath());
Sudheer Shankac7562092018-08-24 10:20:56 -0700380 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
Sudheer Shankaa695f252018-08-03 18:07:52 -0700381 StringAppendF(&primarySource, "/%d", userId);
382 }
383 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
384 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
385 if (errno != ENOENT) {
386 PLOG(WARNING) << "Failed to unlink " << target;
387 }
388 }
389 if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), target.c_str()))) {
390 PLOG(WARNING) << "Failed to link " << primarySource << " at " << target;
391 return -errno;
392 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700393 } else {
394 std::string source(mPrimary->getPath());
395 if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
396 source = StringPrintf("%s/%d", source.c_str(), userId);
397 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
398 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700399
Sudheer Shanka53947a32018-08-01 10:24:13 -0700400 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
401 if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
402 if (errno != ENOENT) {
403 PLOG(WARNING) << "Failed to unlink " << target;
404 }
405 }
406 LOG(DEBUG) << "Linking " << source << " to " << target;
407 if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
408 PLOG(WARNING) << "Failed to link";
409 return -errno;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700410 }
411 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700412 return 0;
413}
414
Sudheer Shankac7562092018-08-24 10:20:56 -0700415int VolumeManager::mountSandboxesForPrimaryVol(userid_t userId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700416 const std::vector<std::string>& packageNames) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700417 std::string primaryRoot(StringPrintf("/mnt/storage/%s", mPrimary->getLabel().c_str()));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700418 bool isPrimaryEmulated = (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated);
Sudheer Shankac7562092018-08-24 10:20:56 -0700419 if (isPrimaryEmulated) {
420 StringAppendF(&primaryRoot, "/%d", userId);
421 if (fs_prepare_dir(primaryRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
422 PLOG(ERROR) << "fs_prepare_dir failed on " << primaryRoot;
423 return -errno;
424 }
425 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700426
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700427 std::string sandboxRoot =
428 prepareSubDirs(primaryRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700429 if (sandboxRoot.empty()) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700430 return -errno;
431 }
Sudheer Shankaf768c272018-08-04 10:10:27 -0700432 std::string sharedSandboxRoot;
433 StringAppendF(&sharedSandboxRoot, "%s/shared", sandboxRoot.c_str());
434 // Create shared sandbox base dir for apps with sharedUserIds
435 if (fs_prepare_dir(sharedSandboxRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
436 PLOG(ERROR) << "fs_prepare_dir failed on " << sharedSandboxRoot;
437 return -errno;
438 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700439
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700440 std::string dataRoot = prepareSubDirs(primaryRoot, "Android/data/", 0700, AID_ROOT, AID_ROOT);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700441 if (dataRoot.empty()) {
442 return -errno;
443 }
444
Sudheer Shankaa695f252018-08-03 18:07:52 -0700445 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
446 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
447 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
448 return -errno;
449 }
450 mntTargetRoot.append("/package");
451 if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
452 PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700453 return -errno;
454 }
455
456 for (auto& packageName : packageNames) {
457 const auto& it = mAppIds.find(packageName);
458 if (it == mAppIds.end()) {
459 PLOG(ERROR) << "appId is not available for " << packageName;
460 continue;
461 }
462 appid_t appId = it->second;
463 std::string sandboxId = mSandboxIds[appId];
464 uid_t uid = multiuser_get_uid(userId, appId);
465
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700466 // Create /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
Sudheer Shanka53947a32018-08-01 10:24:13 -0700467 std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
468 if (pkgSandboxSourceDir.empty()) {
469 return -errno;
470 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700471
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700472 // Create [1] /mnt/storage/emulated/0/Android/data/<packageName>
473 // Create [2] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>/Android/data/<packageName>
Sudheer Shanka53947a32018-08-01 10:24:13 -0700474 // Mount [1] at [2]
475 std::string pkgDataSourceDir = preparePkgDataSource(packageName, uid, dataRoot);
476 if (pkgDataSourceDir.empty()) {
477 return -errno;
478 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700479 std::string pkgDataTargetDir = preparePkgDataTarget(packageName, uid, pkgSandboxSourceDir);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700480 if (pkgDataTargetDir.empty()) {
481 return -errno;
482 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700483 if (TEMP_FAILURE_RETRY(mount(pkgDataSourceDir.c_str(), pkgDataTargetDir.c_str(), nullptr,
484 MS_BIND | MS_REC, nullptr)) == -1) {
485 PLOG(ERROR) << "Failed to mount " << pkgDataSourceDir << " at " << pkgDataTargetDir;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700486 return -errno;
487 }
488
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700489 // Already created [1] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
490 // Create [2] /mnt/user/0/package/<packageName>/emulated/0
491 // Mount [1] at [2]
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700492 std::string pkgSandboxTargetDir = prepareSandboxTarget(
493 packageName, uid, mPrimary->getLabel(), mntTargetRoot, isPrimaryEmulated);
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700494 if (pkgSandboxTargetDir.empty()) {
495 return -errno;
496 }
497
498 if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700499 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700500 PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
501 << pkgSandboxTargetDir;
502 return -errno;
503 }
504
Sudheer Shanka53947a32018-08-01 10:24:13 -0700505 // Create [1] /mnt/user/0/package/<packageName>/self/primary
506 // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
507 // Mount [2] at [1]
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700508 std::string pkgPrimaryTargetDir =
509 prepareSubDirs(StringPrintf("%s/%s", mntTargetRoot.c_str(), packageName.c_str()),
510 "self/primary/", 0755, uid, uid);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700511 if (pkgPrimaryTargetDir.empty()) {
512 return -errno;
513 }
514 if (TEMP_FAILURE_RETRY(mount(pkgSandboxTargetDir.c_str(), pkgPrimaryTargetDir.c_str(),
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700515 nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700516 PLOG(ERROR) << "Failed to mount " << pkgSandboxTargetDir << " at "
517 << pkgPrimaryTargetDir;
518 return -errno;
519 }
520 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700521 return 0;
522}
523
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700524std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
525 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700526 std::string path(pathPrefix);
527 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
528 for (size_t i = 0; i < subDirList.size(); ++i) {
529 std::string subDir = subDirList[i];
530 if (subDir.empty()) {
531 continue;
532 }
533 StringAppendF(&path, "/%s", subDir.c_str());
534 if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
535 PLOG(ERROR) << "fs_prepare_dir failed on " << path;
536 return kEmptyString;
537 }
538 }
539 return path;
540}
541
542std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700543 const std::string& sandboxRootDir) {
Sudheer Shankaf768c272018-08-04 10:10:27 -0700544 std::string sandboxSourceDir(sandboxRootDir);
545 if (android::base::StartsWith(sandboxId, "shared:")) {
546 StringAppendF(&sandboxSourceDir, "/shared/%s", sandboxId.substr(7).c_str());
547 } else {
548 StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
549 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700550 if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
551 PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
552 return kEmptyString;
553 }
554 return sandboxSourceDir;
555}
556
557std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700558 const std::string& volumeLabel,
559 const std::string& mntTargetRootDir,
560 bool isUserDependent) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700561 std::string segment;
562 if (isUserDependent) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700563 segment = StringPrintf("%s/%s/%d/", packageName.c_str(), volumeLabel.c_str(),
564 multiuser_get_user_id(uid));
Sudheer Shanka53947a32018-08-01 10:24:13 -0700565 } else {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700566 segment = StringPrintf("%s/%s/", packageName.c_str(), volumeLabel.c_str());
Sudheer Shanka53947a32018-08-01 10:24:13 -0700567 }
568 return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
569}
570
571std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700572 const std::string& dataRootDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700573 std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
574 if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
575 PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
576 return kEmptyString;
577 }
578 return dataSourceDir;
579}
580
581std::string VolumeManager::preparePkgDataTarget(const std::string& packageName, uid_t uid,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700582 const std::string& pkgSandboxDir) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700583 std::string segment = StringPrintf("Android/data/%s/", packageName.c_str());
584 return prepareSubDirs(pkgSandboxDir, segment.c_str(), 0755, uid, uid);
585}
586
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700587int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
588 mAddedUsers[userId] = userSerialNumber;
589 return 0;
590}
591
592int VolumeManager::onUserRemoved(userid_t userId) {
593 mAddedUsers.erase(userId);
594 return 0;
595}
596
Sudheer Shankaebaad1c2018-07-31 16:39:59 -0700597int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700598 // Note that sometimes the system will spin up processes from Zygote
599 // before actually starting the user, so we're okay if Zygote
600 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600601 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700602 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
603
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700604 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700605 mUserPackages[userId] = packageNames;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700606 if (mPrimary) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700607 linkPrimary(userId, packageNames);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700608 }
609 return 0;
610}
611
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700612int VolumeManager::onUserStopped(userid_t userId) {
613 mStartedUsers.erase(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700614 return 0;
615}
616
Sudheer Shankad484aa92018-07-31 10:07:34 -0700617int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700618 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700619 for (size_t i = 0; i < packageNames.size(); ++i) {
620 mAppIds[packageNames[i]] = appIds[i];
621 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700622 return 0;
623}
624
625int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700626 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700627 for (size_t i = 0; i < appIds.size(); ++i) {
628 mSandboxIds[appIds[i]] = sandboxIds[i];
629 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700630 return 0;
631}
632
Sudheer Shankac7562092018-08-24 10:20:56 -0700633int VolumeManager::mountExternalStorageForApp(const std::string& packageName, appid_t appId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700634 const std::string& sandboxId, userid_t userId) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700635 if (!GetBoolProperty(kIsolatedStorage, false)) {
636 return 0;
637 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
638 // User not started, no need to do anything now. Required bind mounts for the package will
639 // be created when the user starts.
640 return 0;
641 }
642 mUserPackages[userId].push_back(packageName);
643 mAppIds[packageName] = appId;
644 mSandboxIds[appId] = sandboxId;
645 if (mPrimary) {
646 return mountSandboxesForPrimaryVol(userId, {packageName});
647 }
648 return 0;
649}
650
Jeff Sharkey401b2602017-12-14 22:15:20 -0700651int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
652 mSecureKeyguardShowing = isShowing;
653 if (!mSecureKeyguardShowing) {
654 // Now that secure keyguard has been dismissed, process
655 // any pending disks
656 for (const auto& disk : mPendingDisks) {
657 disk->create();
658 mDisks.push_back(disk);
659 }
660 mPendingDisks.clear();
661 }
662 return 0;
663}
664
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700665int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
666 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700667 for (userid_t userId : mStartedUsers) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700668 linkPrimary(userId, mUserPackages[userId]);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700669 }
670 return 0;
671}
672
Jeff Sharkey3472e522017-10-06 18:02:53 -0600673static int unmount_tree(const std::string& prefix) {
Sudheer Shanka89ddf992018-09-25 14:22:07 -0700674 return android::vold::UnmountTree(prefix);
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700675}
676
Jeff Sharkey66270a22015-06-24 11:49:24 -0700677int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700678 // If the isolated storage is enabled, return -1 since in the isolated storage world, there
679 // are no longer any runtime storage permissions, so this shouldn't be called anymore.
680 if (GetBoolProperty(kIsolatedStorage, false)) {
681 return -1;
682 }
Jeff Sharkey66270a22015-06-24 11:49:24 -0700683 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
684
685 DIR* dir;
686 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600687 std::string rootName;
688 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700689 int pidFd;
690 int nsFd;
691 struct stat sb;
692 pid_t child;
693
694 if (!(dir = opendir("/proc"))) {
695 PLOG(ERROR) << "Failed to opendir";
696 return -1;
697 }
698
699 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -0600700 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
701 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700702 closedir(dir);
703 return -1;
704 }
705
706 // Poke through all running PIDs look for apps running as UID
707 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -0700708 pid_t pid;
709 if (de->d_type != DT_DIR) continue;
710 if (!android::base::ParseInt(de->d_name, &pid)) continue;
711
Jeff Sharkey66270a22015-06-24 11:49:24 -0700712 pidFd = -1;
713 nsFd = -1;
714
715 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
716 if (pidFd < 0) {
717 goto next;
718 }
719 if (fstat(pidFd, &sb) != 0) {
720 PLOG(WARNING) << "Failed to stat " << de->d_name;
721 goto next;
722 }
723 if (sb.st_uid != uid) {
724 goto next;
725 }
726
727 // Matches so far, but refuse to touch if in root namespace
728 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -0600729 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700730 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
731 goto next;
732 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600733 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -0700734 LOG(WARNING) << "Skipping due to root namespace";
735 goto next;
736 }
737
738 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700739 nsFd = openat(pidFd, "ns/mnt", O_RDONLY); // not O_CLOEXEC
Jeff Sharkey66270a22015-06-24 11:49:24 -0700740 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700741 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700742 goto next;
743 }
744
745 if (!(child = fork())) {
746 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700747 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -0700748 _exit(1);
749 }
750
Jeff Sharkey3472e522017-10-06 18:02:53 -0600751 unmount_tree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -0700752
753 std::string storageSource;
754 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700755 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700756 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700757 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700758 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -0700759 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -0700760 } else {
761 // Sane default of no storage visible
762 _exit(0);
763 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700764 if (TEMP_FAILURE_RETRY(
765 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
766 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700767 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -0700768 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700769 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
770 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +0900771 _exit(1);
772 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700773
774 // Mount user-specific symlink helper into place
775 userid_t user_id = multiuser_get_user_id(uid);
776 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700777 if (TEMP_FAILURE_RETRY(
778 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
779 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -0700780 _exit(1);
781 }
782
Jeff Sharkey66270a22015-06-24 11:49:24 -0700783 _exit(0);
784 }
785
786 if (child == -1) {
787 PLOG(ERROR) << "Failed to fork";
788 goto next;
789 } else {
790 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
791 }
792
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700793 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -0700794 close(nsFd);
795 close(pidFd);
796 }
797 closedir(dir);
798 return 0;
799}
800
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700801int VolumeManager::reset() {
802 // Tear down all existing disks/volumes and start from a blank slate so
803 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +0800804 if (mInternalEmulated != nullptr) {
805 mInternalEmulated->destroy();
806 mInternalEmulated->create();
807 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700808 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700809 disk->destroy();
810 disk->create();
811 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600812 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700813 mAddedUsers.clear();
814 mStartedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700815
816 mUserPackages.clear();
817 mAppIds.clear();
818 mSandboxIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700819
820 // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
821 unmount_tree("/mnt/user/");
822 // For unmounting dirs under /mnt/storage including the bind mount at /mnt/storage, that's
823 // why no trailing '/'
824 unmount_tree("/mnt/storage");
825 mMntStorageCreated = false;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700826 return 0;
827}
828
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700829// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700830int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700831 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700832 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700833 }
Paul Crowley56292ef2017-10-20 08:07:53 -0700834 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700835 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -0700836 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700837 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700838 disk->destroy();
839 }
840 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700841 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -0700842 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700843 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -0700844}
845
Jeff Sharkey9c484982015-03-31 10:35:33 -0700846int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700847 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600848 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700849
Jeff Sharkey9c484982015-03-31 10:35:33 -0700850 // First, try gracefully unmounting all known devices
851 if (mInternalEmulated != nullptr) {
852 mInternalEmulated->unmount();
853 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700854 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -0700855 disk->unmountAll();
856 }
857
858 // Worst case we might have some stale mounts lurking around, so
859 // force unmount those just to be safe.
860 FILE* fp = setmntent("/proc/mounts", "r");
861 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600862 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -0700863 return -errno;
864 }
865
866 // Some volumes can be stacked on each other, so force unmount in
867 // reverse order to give us the best chance of success.
868 std::list<std::string> toUnmount;
869 mntent* mentry;
870 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600871 auto test = std::string(mentry->mnt_dir);
Tri Vobca5cd72018-04-16 14:27:10 -0700872 if ((android::base::StartsWith(test, "/mnt/") &&
Bowgo Tsaic0cd37b2018-06-29 10:31:07 +0800873 !android::base::StartsWith(test, "/mnt/vendor") &&
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700874 !android::base::StartsWith(test, "/mnt/product") &&
875 !android::base::StartsWith(test, "/mnt/storage")) ||
Tri Vobca5cd72018-04-16 14:27:10 -0700876 android::base::StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600877 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -0700878 }
879 }
880 endmntent(fp);
881
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700882 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600883 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -0700884 android::vold::ForceUnmount(path);
885 }
886
887 return 0;
888}
889
Jeff Sharkey3472e522017-10-06 18:02:53 -0600890int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700891 // Only offer to create directories for paths managed by vold
Jeff Sharkey3472e522017-10-06 18:02:53 -0600892 if (android::base::StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700893 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -0600894 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700895 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600896 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700897 return -EINVAL;
898 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -0700899}
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600900
901static size_t kAppFuseMaxMountPointName = 32;
902
903static android::status_t getMountPath(uid_t uid, const std::string& name, std::string* path) {
904 if (name.size() > kAppFuseMaxMountPointName) {
905 LOG(ERROR) << "AppFuse mount name is too long.";
906 return -EINVAL;
907 }
908 for (size_t i = 0; i < name.size(); i++) {
909 if (!isalnum(name[i])) {
910 LOG(ERROR) << "AppFuse mount name contains invalid character.";
911 return -EINVAL;
912 }
913 }
914 *path = android::base::StringPrintf("/mnt/appfuse/%d_%s", uid, name.c_str());
915 return android::OK;
916}
917
918static android::status_t mountInNamespace(uid_t uid, int device_fd, const std::string& path) {
919 // Remove existing mount.
920 android::vold::ForceUnmount(path);
921
922 const auto opts = android::base::StringPrintf(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700923 "fd=%i,"
924 "rootmode=40000,"
925 "default_permissions,"
926 "allow_other,"
927 "user_id=%d,group_id=%d,"
928 "context=\"u:object_r:app_fuse_file:s0\","
929 "fscontext=u:object_r:app_fusefs:s0",
930 device_fd, uid, uid);
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600931
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700932 const int result =
933 TEMP_FAILURE_RETRY(mount("/dev/fuse", path.c_str(), "fuse",
934 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME, opts.c_str()));
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600935 if (result != 0) {
936 PLOG(ERROR) << "Failed to mount " << path;
937 return -errno;
938 }
939
940 return android::OK;
941}
942
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700943static android::status_t runCommandInNamespace(const std::string& command, uid_t uid, pid_t pid,
944 const std::string& path, int device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600945 if (DEBUG_APPFUSE) {
946 LOG(DEBUG) << "Run app fuse command " << command << " for the path " << path
947 << " in namespace " << uid;
948 }
949
950 unique_fd dir(open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
951 if (dir.get() == -1) {
952 PLOG(ERROR) << "Failed to open /proc";
953 return -errno;
954 }
955
956 // Obtains process file descriptor.
957 const std::string pid_str = android::base::StringPrintf("%d", pid);
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700958 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 -0600959 if (pid_fd.get() == -1) {
960 PLOG(ERROR) << "Failed to open /proc/" << pid;
961 return -errno;
962 }
963
964 // Check UID of process.
965 {
966 struct stat sb;
967 const int result = fstat(pid_fd.get(), &sb);
968 if (result == -1) {
969 PLOG(ERROR) << "Failed to stat /proc/" << pid;
970 return -errno;
971 }
972 if (sb.st_uid != AID_SYSTEM) {
973 LOG(ERROR) << "Only system can mount appfuse. UID expected=" << AID_SYSTEM
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700974 << ", actual=" << sb.st_uid;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600975 return -EPERM;
976 }
977 }
978
979 // Matches so far, but refuse to touch if in root namespace
980 {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600981 std::string rootName;
982 std::string pidName;
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700983 if (!android::vold::Readlinkat(dir.get(), "1/ns/mnt", &rootName) ||
984 !android::vold::Readlinkat(pid_fd.get(), "ns/mnt", &pidName)) {
Jeff Sharkey3472e522017-10-06 18:02:53 -0600985 PLOG(ERROR) << "Failed to read namespaces";
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600986 return -EPERM;
987 }
Jeff Sharkey3472e522017-10-06 18:02:53 -0600988 if (rootName == pidName) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600989 LOG(ERROR) << "Don't mount appfuse in root namespace";
990 return -EPERM;
991 }
992 }
993
994 // We purposefully leave the namespace open across the fork
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700995 unique_fd ns_fd(openat(pid_fd.get(), "ns/mnt", O_RDONLY)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600996 if (ns_fd.get() < 0) {
997 PLOG(ERROR) << "Failed to open namespace for /proc/" << pid << "/ns/mnt";
998 return -errno;
999 }
1000
1001 int child = fork();
1002 if (child == 0) {
1003 if (setns(ns_fd.get(), CLONE_NEWNS) != 0) {
1004 PLOG(ERROR) << "Failed to setns";
1005 _exit(-errno);
1006 }
1007
1008 if (command == "mount") {
1009 _exit(mountInNamespace(uid, device_fd, path));
1010 } else if (command == "unmount") {
1011 // If it's just after all FD opened on mount point are closed, umount2 can fail with
1012 // EBUSY. To avoid the case, specify MNT_DETACH.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001013 if (umount2(path.c_str(), UMOUNT_NOFOLLOW | MNT_DETACH) != 0 && errno != EINVAL &&
1014 errno != ENOENT) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001015 PLOG(ERROR) << "Failed to unmount directory.";
1016 _exit(-errno);
1017 }
1018 if (rmdir(path.c_str()) != 0) {
1019 PLOG(ERROR) << "Failed to remove the mount directory.";
1020 _exit(-errno);
1021 }
1022 _exit(android::OK);
1023 } else {
1024 LOG(ERROR) << "Unknown appfuse command " << command;
1025 _exit(-EPERM);
1026 }
1027 }
1028
1029 if (child == -1) {
1030 PLOG(ERROR) << "Failed to folk child process";
1031 return -errno;
1032 }
1033
1034 android::status_t status;
1035 TEMP_FAILURE_RETRY(waitpid(child, &status, 0));
1036
1037 return status;
1038}
1039
1040int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001041 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001042 int id = mNextObbId++;
1043
1044 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001045 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001046 vol->create();
1047
1048 mObbVolumes.push_back(vol);
1049 *outVolId = vol->getId();
1050 return android::OK;
1051}
1052
1053int VolumeManager::destroyObb(const std::string& volId) {
1054 auto i = mObbVolumes.begin();
1055 while (i != mObbVolumes.end()) {
1056 if ((*i)->getId() == volId) {
1057 (*i)->destroy();
1058 i = mObbVolumes.erase(i);
1059 } else {
1060 ++i;
1061 }
1062 }
1063 return android::OK;
1064}
1065
1066int VolumeManager::mountAppFuse(uid_t uid, pid_t pid, int mountId,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001067 android::base::unique_fd* device_fd) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001068 std::string name = std::to_string(mountId);
1069
1070 // Check mount point name.
1071 std::string path;
1072 if (getMountPath(uid, name, &path) != android::OK) {
1073 LOG(ERROR) << "Invalid mount point name";
1074 return -1;
1075 }
1076
1077 // Create directories.
1078 const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
1079 if (result != android::OK) {
1080 PLOG(ERROR) << "Failed to prepare directory " << path;
1081 return -1;
1082 }
1083
1084 // Open device FD.
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001085 device_fd->reset(open("/dev/fuse", O_RDWR)); // not O_CLOEXEC
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001086 if (device_fd->get() == -1) {
1087 PLOG(ERROR) << "Failed to open /dev/fuse";
1088 return -1;
1089 }
1090
1091 // Mount.
1092 return runCommandInNamespace("mount", uid, pid, path, device_fd->get());
1093}
1094
1095int VolumeManager::unmountAppFuse(uid_t uid, pid_t pid, int mountId) {
1096 std::string name = std::to_string(mountId);
1097
1098 // Check mount point name.
1099 std::string path;
1100 if (getMountPath(uid, name, &path) != android::OK) {
1101 LOG(ERROR) << "Invalid mount point name";
1102 return -1;
1103 }
1104
1105 return runCommandInNamespace("unmount", uid, pid, path, -1 /* device_fd */);
1106}