blob: a6ead9d4fc2d5e5afdbe029a3570185f570bafce [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>
Sudheer Shanka40ab6742018-09-18 13:07:45 -070033#include <array>
San Mehata19b2502010-01-06 10:33:53 -080034
San Mehata2677e42009-12-13 10:40:18 -080035#include <linux/kdev_t.h>
San Mehatf1b736b2009-10-10 17:22:08 -070036
Jiyong Park8d21c922019-01-04 13:35:25 +090037#include <ApexProperties.sysprop.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080038#include <android-base/logging.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070039#include <android-base/parseint.h>
Jeff Sharkey3472e522017-10-06 18:02:53 -060040#include <android-base/properties.h>
Elliott Hughes7e128fb2015-12-04 15:50:53 -080041#include <android-base/stringprintf.h>
Jeff Vander Stoep58890832017-10-23 17:12:31 -070042#include <android-base/strings.h>
43
Jeff Sharkey71ebe152013-09-17 17:24:38 -070044#include <cutils/fs.h>
Jeff Sharkey67b8c492017-09-21 17:08:43 -060045#include <utils/Trace.h>
San Mehatf1b736b2009-10-10 17:22:08 -070046
Robert Craigb9e3ba52014-02-04 10:53:00 -050047#include <selinux/android.h>
48
San Mehatfd7f5872009-10-12 11:32:47 -070049#include <sysutils/NetlinkEvent.h>
50
Kenny Root344ca102012-04-03 17:23:01 -070051#include <private/android_filesystem_config.h>
52
Eric Biggersa701c452018-10-23 13:06:55 -070053#include <fscrypt/fscrypt.h>
Paul Crowleyc6433a22017-10-24 14:54:43 -070054
Risanac02a482018-10-31 21:59:47 -060055#include "AppFuseUtil.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070056#include "Devmapper.h"
Eric Biggersa701c452018-10-23 13:06:55 -070057#include "FsCrypt.h"
San Mehata19b2502010-01-06 10:33:53 -080058#include "Loop.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070059#include "NetlinkManager.h"
60#include "Process.h"
61#include "Utils.h"
Sudheer Shanka40ab6742018-09-18 13:07:45 -070062#include "VoldNativeService.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070063#include "VoldUtil.h"
64#include "VolumeManager.h"
65#include "cryptfs.h"
Jeff Sharkeyd0640f62015-05-21 22:35:42 -070066#include "fs/Ext4.h"
67#include "fs/Vfat.h"
Paul Crowleyc6433a22017-10-24 14:54:43 -070068#include "model/EmulatedVolume.h"
69#include "model/ObbVolume.h"
Risan8c9f3322018-10-29 08:52:56 +090070#include "model/StubVolume.h"
San Mehat23969932010-01-09 07:08:06 -080071
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000072using android::OK;
Sudheer Shanka53947a32018-08-01 10:24:13 -070073using android::base::GetBoolProperty;
Mark Salyzyn86e81e72018-09-20 10:09:27 -070074using android::base::StartsWith;
Sudheer Shanka53947a32018-08-01 10:24:13 -070075using android::base::StringAppendF;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070076using android::base::StringPrintf;
Jeff Sharkey11c2d382017-09-11 10:32:01 -060077using android::base::unique_fd;
Sudheer Shanka023b5392019-02-06 12:39:19 -080078using android::vold::BindMount;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +000079using android::vold::CreateDir;
Sudheer Shanka30df1c62019-02-22 17:03:02 -080080using android::vold::DeleteDirContents;
Sudheer Shanka023b5392019-02-06 12:39:19 -080081using android::vold::DeleteDirContentsAndDir;
82using android::vold::Symlink;
83using android::vold::Unlink;
84using android::vold::UnmountTree;
Sudheer Shanka03992e32018-12-12 12:43:38 -080085using android::vold::VoldNativeService;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070086
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060087static const char* kPathUserMount = "/mnt/user";
88static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
89
Sudheer Shanka53947a32018-08-01 10:24:13 -070090static const char* kIsolatedStorage = "persist.sys.isolated_storage";
Sudheer Shanka34b437b2019-01-17 17:20:47 -080091static const char* kIsolatedStorageSnapshot = "sys.isolated_storage_snapshot";
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060092static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
93
Sudheer Shanka53947a32018-08-01 10:24:13 -070094static const std::string kEmptyString("");
95
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -060096/* 512MiB is large enough for testing purposes */
97static const unsigned int kSizeVirtualDisk = 536870912;
Jeff Sharkey36801cc2015-03-13 16:09:20 -070098
Jeff Sharkey36801cc2015-03-13 16:09:20 -070099static const unsigned int kMajorBlockMmc = 179;
Yu Ning942d4e82016-01-08 17:36:47 +0800100static const unsigned int kMajorBlockExperimentalMin = 240;
101static const unsigned int kMajorBlockExperimentalMax = 254;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700102
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700103VolumeManager* VolumeManager::sInstance = NULL;
San Mehatf1b736b2009-10-10 17:22:08 -0700104
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700105VolumeManager* VolumeManager::Instance() {
106 if (!sInstance) sInstance = new VolumeManager();
San Mehatf1b736b2009-10-10 17:22:08 -0700107 return sInstance;
108}
109
110VolumeManager::VolumeManager() {
San Mehatd9a4e352010-03-12 13:32:47 -0800111 mDebug = false;
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600112 mNextObbId = 0;
Risan8c9f3322018-10-29 08:52:56 +0900113 mNextStubVolumeId = 0;
Jeff Sharkey401b2602017-12-14 22:15:20 -0700114 // For security reasons, assume that a secure keyguard is
115 // showing until we hear otherwise
116 mSecureKeyguardShowing = true;
San Mehatf1b736b2009-10-10 17:22:08 -0700117}
118
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700119VolumeManager::~VolumeManager() {}
San Mehatd9a4e352010-03-12 13:32:47 -0800120
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800121static bool hasIsolatedStorage() {
Sudheer Shankaa05ea742019-04-12 13:55:28 -0700122 return false &&
123 GetBoolProperty(kIsolatedStorageSnapshot, GetBoolProperty(kIsolatedStorage, true));
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800124}
125
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600126int VolumeManager::updateVirtualDisk() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600127 ATRACE_NAME("VolumeManager::updateVirtualDisk");
Mark Salyzyn86e81e72018-09-20 10:09:27 -0700128 if (GetBoolProperty(kPropVirtualDisk, false)) {
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600129 if (access(kPathVirtualDisk, F_OK) != 0) {
130 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
131 }
132
133 if (mVirtualDisk == nullptr) {
134 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
135 LOG(ERROR) << "Failed to create virtual disk";
136 return -1;
137 }
138
139 struct stat buf;
140 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
141 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
142 return -1;
143 }
144
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700145 auto disk = new android::vold::Disk(
146 "virtual", buf.st_rdev, "virtual",
147 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600148 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
Jeff Sharkey401b2602017-12-14 22:15:20 -0700149 handleDiskAdded(mVirtualDisk);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600150 }
151 } else {
152 if (mVirtualDisk != nullptr) {
153 dev_t device = mVirtualDisk->getDevice();
Jeff Sharkey401b2602017-12-14 22:15:20 -0700154 handleDiskRemoved(device);
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600155
156 Loop::destroyByDevice(mVirtualDiskPath.c_str());
157 mVirtualDisk = nullptr;
158 }
159
160 if (access(kPathVirtualDisk, F_OK) == 0) {
161 unlink(kPathVirtualDisk);
162 }
163 }
164 return 0;
165}
166
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700167int VolumeManager::setDebug(bool enable) {
San Mehatd9a4e352010-03-12 13:32:47 -0800168 mDebug = enable;
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700169 return 0;
San Mehatd9a4e352010-03-12 13:32:47 -0800170}
171
San Mehatf1b736b2009-10-10 17:22:08 -0700172int VolumeManager::start() {
Jeff Sharkey67b8c492017-09-21 17:08:43 -0600173 ATRACE_NAME("VolumeManager::start");
174
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700175 // Always start from a clean slate by unmounting everything in
176 // directories that we own, in case we crashed.
Jeff Sharkey9c484982015-03-31 10:35:33 -0700177 unmountAll();
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700178
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600179 Devmapper::destroyAll();
180 Loop::destroyAll();
181
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700182 // Assume that we always have an emulated volume on internal
183 // storage; the framework will decide if it should be mounted.
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700184 CHECK(mInternalEmulated == nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700185 mInternalEmulated = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700186 new android::vold::EmulatedVolume("/data/media"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700187 mInternalEmulated->create();
188
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600189 // Consider creating a virtual disk
190 updateVirtualDisk();
191
San Mehatf1b736b2009-10-10 17:22:08 -0700192 return 0;
193}
194
195int VolumeManager::stop() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700196 CHECK(mInternalEmulated != nullptr);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700197 mInternalEmulated->destroy();
198 mInternalEmulated = nullptr;
San Mehatf1b736b2009-10-10 17:22:08 -0700199 return 0;
200}
201
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700202void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -0700203 std::lock_guard<std::mutex> lock(mLock);
204
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700205 if (mDebug) {
Sudheer Shanka4b6ca4e2018-09-21 10:54:54 -0700206 LOG(DEBUG) << "----------------";
207 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
Jeff Sharkeyf1b996d2015-04-17 17:35:20 -0700208 evt->dump();
209 }
San Mehatf1b736b2009-10-10 17:22:08 -0700210
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700211 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
212 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700213
214 if (devType != "disk") return;
215
Jeff Sharkey95440eb2017-09-18 18:19:28 -0600216 int major = std::stoi(evt->findParam("MAJOR"));
217 int minor = std::stoi(evt->findParam("MINOR"));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700218 dev_t device = makedev(major, minor);
219
220 switch (evt->getAction()) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700221 case NetlinkEvent::Action::kAdd: {
222 for (const auto& source : mDiskSources) {
223 if (source->matches(eventPath)) {
224 // For now, assume that MMC and virtio-blk (the latter is
225 // emulator-specific; see Disk.cpp for details) devices are SD,
226 // and that everything else is USB
227 int flags = source->getFlags();
228 if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
229 major >= (int)kMajorBlockExperimentalMin &&
230 major <= (int)kMajorBlockExperimentalMax)) {
231 flags |= android::vold::Disk::Flags::kSd;
232 } else {
233 flags |= android::vold::Disk::Flags::kUsb;
234 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700235
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700236 auto disk =
237 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
238 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
239 break;
240 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700241 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700242 break;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700243 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700244 case NetlinkEvent::Action::kChange: {
245 LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
246 handleDiskChanged(device);
247 break;
248 }
249 case NetlinkEvent::Action::kRemove: {
250 handleDiskRemoved(device);
251 break;
252 }
253 default: {
254 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
255 break;
256 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700257 }
258}
259
Jeff Sharkey401b2602017-12-14 22:15:20 -0700260void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
261 // For security reasons, if secure keyguard is showing, wait
262 // until the user unlocks the device to actually touch it
263 if (mSecureKeyguardShowing) {
264 LOG(INFO) << "Found disk at " << disk->getEventPath()
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700265 << " but delaying scan due to secure keyguard";
Jeff Sharkey401b2602017-12-14 22:15:20 -0700266 mPendingDisks.push_back(disk);
267 } else {
268 disk->create();
269 mDisks.push_back(disk);
270 }
271}
272
273void VolumeManager::handleDiskChanged(dev_t device) {
274 for (const auto& disk : mDisks) {
275 if (disk->getDevice() == device) {
276 disk->readMetadata();
277 disk->readPartitions();
278 }
279 }
280
281 // For security reasons, we ignore all pending disks, since
282 // we'll scan them once the device is unlocked
283}
284
285void VolumeManager::handleDiskRemoved(dev_t device) {
286 auto i = mDisks.begin();
287 while (i != mDisks.end()) {
288 if ((*i)->getDevice() == device) {
289 (*i)->destroy();
290 i = mDisks.erase(i);
291 } else {
292 ++i;
293 }
294 }
295 auto j = mPendingDisks.begin();
296 while (j != mPendingDisks.end()) {
297 if ((*j)->getDevice() == device) {
298 j = mPendingDisks.erase(j);
299 } else {
300 ++j;
301 }
302 }
303}
304
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700305void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
Wei Wang6b455c22017-01-20 11:52:33 -0800306 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700307 mDiskSources.push_back(diskSource);
308}
309
310std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
311 for (auto disk : mDisks) {
312 if (disk->getId() == id) {
313 return disk;
San Mehatf1b736b2009-10-10 17:22:08 -0700314 }
315 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700316 return nullptr;
317}
San Mehatf1b736b2009-10-10 17:22:08 -0700318
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700319std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
Gao Xiangd263da82017-08-14 11:32:13 +0800320 // Vold could receive "mount" after "shutdown" command in the extreme case.
321 // If this happens, mInternalEmulated will equal nullptr and
322 // we need to deal with it in order to avoid null pointer crash.
323 if (mInternalEmulated != nullptr && mInternalEmulated->getId() == id) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700324 return mInternalEmulated;
San Mehatf1b736b2009-10-10 17:22:08 -0700325 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700326 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700327 auto vol = disk->findVolume(id);
328 if (vol != nullptr) {
329 return vol;
330 }
331 }
Risan8c9f3322018-10-29 08:52:56 +0900332 for (const auto& vol : mStubVolumes) {
333 if (vol->getId() == id) {
334 return vol;
335 }
336 }
Jeff Sharkey11c2d382017-09-11 10:32:01 -0600337 for (const auto& vol : mObbVolumes) {
338 if (vol->getId() == id) {
339 return vol;
340 }
341 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700342 return nullptr;
343}
344
Greg Kaiser2bc201e2018-12-18 08:42:08 -0800345void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
346 std::list<std::string>& list) const {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700347 list.clear();
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -0700348 for (const auto& disk : mDisks) {
Jeff Sharkeyc86ab6f2015-06-26 14:02:09 -0700349 disk->listVolumes(type, list);
350 }
351}
352
Jeff Sharkey3ce18252017-10-24 11:08:45 -0600353int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700354 std::string normalizedGuid;
355 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
356 LOG(WARNING) << "Invalid GUID " << partGuid;
357 return -1;
358 }
359
Paul Crowleyc6433a22017-10-24 14:54:43 -0700360 bool success = true;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700361 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
362 if (unlink(keyPath.c_str()) != 0) {
363 LOG(ERROR) << "Failed to unlink " << keyPath;
Paul Crowleyc6433a22017-10-24 14:54:43 -0700364 success = false;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700365 }
Eric Biggersa701c452018-10-23 13:06:55 -0700366 if (fscrypt_is_native()) {
367 if (!fscrypt_destroy_volume_keys(fsUuid)) {
Paul Crowleyc6433a22017-10-24 14:54:43 -0700368 success = false;
369 }
370 }
371 return success ? 0 : -1;
Jeff Sharkeybc40cc82015-06-18 14:25:08 -0700372}
373
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700374int VolumeManager::linkPrimary(userid_t userId) {
375 std::string source(mPrimary->getPath());
376 if (mPrimary->isEmulated()) {
377 source = StringPrintf("%s/%d", source.c_str(), userId);
378 fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
379 }
380
381 std::string target(StringPrintf("/mnt/user/%d/primary", userId));
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700382 LOG(DEBUG) << "Linking " << source << " to " << target;
Sudheer Shanka023b5392019-02-06 12:39:19 -0800383 Symlink(source, target);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700384 return 0;
385}
386
387int VolumeManager::mountPkgSpecificDir(const std::string& mntSourceRoot,
388 const std::string& mntTargetRoot,
389 const std::string& packageName, const char* dirName) {
390 std::string mntSourceDir =
391 StringPrintf("%s/Android/%s/%s", mntSourceRoot.c_str(), dirName, packageName.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000392 if (CreateDir(mntSourceDir, 0755) < 0) {
393 return -errno;
394 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700395 std::string mntTargetDir =
396 StringPrintf("%s/Android/%s/%s", mntTargetRoot.c_str(), dirName, packageName.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000397 if (CreateDir(mntTargetDir, 0755) < 0) {
398 return -errno;
399 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800400 return BindMount(mntSourceDir, mntTargetDir);
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700401}
402
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700403int VolumeManager::mountPkgSpecificDirsForRunningProcs(
404 userid_t userId, const std::vector<std::string>& packageNames,
Sudheer Shanka817b9112018-12-13 17:40:28 -0800405 const std::vector<std::string>& visibleVolLabels, int remountMode) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700406 std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir("/proc"), closedir);
407 if (!dirp) {
408 PLOG(ERROR) << "Failed to opendir /proc";
409 return -1;
Sudheer Shankac7562092018-08-24 10:20:56 -0700410 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700411
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700412 std::string rootName;
413 // Figure out root namespace to compare against below
414 if (!android::vold::Readlinkat(dirfd(dirp.get()), "1/ns/mnt", &rootName)) {
415 PLOG(ERROR) << "Failed to read root namespace";
416 return -1;
Sudheer Shankaf768c272018-08-04 10:10:27 -0700417 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700418
Sudheer Shanka55049012019-01-09 12:15:15 -0800419 struct stat mntFullSb;
420 struct stat mntWriteSb;
421 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/full", &mntFullSb)) == -1) {
422 PLOG(ERROR) << "Failed to stat /mnt/runtime/full";
423 return -1;
424 }
425 if (TEMP_FAILURE_RETRY(stat("/mnt/runtime/write", &mntWriteSb)) == -1) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700426 PLOG(ERROR) << "Failed to stat /mnt/runtime/write";
427 return -1;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700428 }
429
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800430 std::string obbMountDir = StringPrintf("/mnt/user/%d/obb_mount", userId);
431 if (fs_prepare_dir(obbMountDir.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
432 PLOG(ERROR) << "Failed to fs_prepare_dir " << obbMountDir;
433 return -1;
434 }
435 const unique_fd obbMountDirFd(
436 TEMP_FAILURE_RETRY(open(obbMountDir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)));
437 if (obbMountDirFd.get() < 0) {
438 PLOG(ERROR) << "Failed to open " << obbMountDir;
439 return -1;
440 }
441
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700442 std::unordered_set<appid_t> validAppIds;
443 for (auto& package : packageNames) {
444 validAppIds.insert(mAppIds[package]);
Sudheer Shankaa695f252018-08-03 18:07:52 -0700445 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700446 std::vector<std::string>& userPackages = mUserPackages[userId];
Sudheer Shanka53947a32018-08-01 10:24:13 -0700447
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800448 std::vector<pid_t> childPids;
449
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700450 struct dirent* de;
451 // Poke through all running PIDs look for apps running in userId
452 while ((de = readdir(dirp.get()))) {
453 pid_t pid;
454 if (de->d_type != DT_DIR) continue;
455 if (!android::base::ParseInt(de->d_name, &pid)) continue;
456
457 const unique_fd pidFd(
458 openat(dirfd(dirp.get()), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC));
459 if (pidFd.get() < 0) {
460 PLOG(WARNING) << "Failed to open /proc/" << pid;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700461 continue;
462 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700463 struct stat sb;
464 if (fstat(pidFd.get(), &sb) != 0) {
465 PLOG(WARNING) << "Failed to stat " << de->d_name;
466 continue;
467 }
468 if (multiuser_get_user_id(sb.st_uid) != userId) {
469 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700470 }
Sudheer Shanka53947a32018-08-01 10:24:13 -0700471
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700472 // Matches so far, but refuse to touch if in root namespace
473 LOG(VERBOSE) << "Found matching PID " << de->d_name;
474 std::string pidName;
475 if (!android::vold::Readlinkat(pidFd.get(), "ns/mnt", &pidName)) {
476 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
477 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700478 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700479 if (rootName == pidName) {
480 LOG(WARNING) << "Skipping due to root namespace";
481 continue;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700482 }
483
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700484 // Only update the mount points of processes running with one of validAppIds.
485 // This should skip any isolated uids.
486 appid_t appId = multiuser_get_app_id(sb.st_uid);
487 if (validAppIds.find(appId) == validAppIds.end()) {
488 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700489 }
490
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700491 std::vector<std::string> packagesForUid;
492 for (auto& package : userPackages) {
493 if (mAppIds[package] == appId) {
494 packagesForUid.push_back(package);
495 }
496 }
497 if (packagesForUid.empty()) {
498 continue;
499 }
500 const std::string& sandboxId = mSandboxIds[appId];
501
502 // We purposefully leave the namespace open across the fork
Nick Kralevich58e1a812019-03-29 18:35:22 -0700503 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
504 unique_fd nsFd(openat(pidFd.get(), "ns/mnt", O_RDONLY));
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700505 if (nsFd.get() < 0) {
506 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
507 continue;
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -0700508 }
509
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700510 pid_t child;
511 if (!(child = fork())) {
512 if (setns(nsFd.get(), CLONE_NEWNS) != 0) {
513 PLOG(ERROR) << "Failed to setns for " << de->d_name;
514 _exit(1);
515 }
516
Sudheer Shanka817b9112018-12-13 17:40:28 -0800517 int mountMode;
518 if (remountMode == -1) {
Sudheer Shanka55049012019-01-09 12:15:15 -0800519 mountMode =
520 getMountModeForRunningProc(packagesForUid, userId, mntWriteSb, mntFullSb);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800521 if (mountMode == -1) {
522 _exit(1);
523 }
524 } else {
525 mountMode = remountMode;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800526 if (handleMountModeInstaller(mountMode, obbMountDirFd.get(), obbMountDir,
527 sandboxId) < 0) {
528 _exit(1);
Sudheer Shanka817b9112018-12-13 17:40:28 -0800529 }
530 }
531 if (mountMode == VoldNativeService::REMOUNT_MODE_FULL ||
Sudheer Shanka55049012019-01-09 12:15:15 -0800532 mountMode == VoldNativeService::REMOUNT_MODE_LEGACY ||
Sudheer Shanka817b9112018-12-13 17:40:28 -0800533 mountMode == VoldNativeService::REMOUNT_MODE_NONE) {
534 // These mount modes are not going to change dynamically, so don't bother
535 // unmounting/remounting dirs.
536 _exit(0);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700537 }
538
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700539 for (auto& volumeLabel : visibleVolLabels) {
540 std::string mntSource = StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str());
541 std::string mntTarget = StringPrintf("/storage/%s", volumeLabel.c_str());
542 if (volumeLabel == "emulated") {
543 StringAppendF(&mntSource, "/%d", userId);
544 StringAppendF(&mntTarget, "/%d", userId);
545 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800546
547 std::string sandboxSource =
548 StringPrintf("%s/Android/sandbox/%s", mntSource.c_str(), sandboxId.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000549 if (CreateDir(sandboxSource, 0755) < 0) {
550 continue;
551 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800552 if (BindMount(sandboxSource, mntTarget) < 0) {
553 continue;
554 }
555
Sudheer Shanka817b9112018-12-13 17:40:28 -0800556 std::string obbSourceDir = StringPrintf("%s/Android/obb", mntSource.c_str());
557 std::string obbTargetDir = StringPrintf("%s/Android/obb", mntTarget.c_str());
Sudheer Shanka023b5392019-02-06 12:39:19 -0800558 if (UnmountTree(obbTargetDir) < 0) {
Sudheer Shanka817b9112018-12-13 17:40:28 -0800559 continue;
560 }
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000561 if (!createPkgSpecificDirRoots(mntSource) || !createPkgSpecificDirRoots(mntTarget)) {
562 continue;
563 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700564 for (auto& package : packagesForUid) {
565 mountPkgSpecificDir(mntSource, mntTarget, package, "data");
566 mountPkgSpecificDir(mntSource, mntTarget, package, "media");
Sudheer Shanka03992e32018-12-12 12:43:38 -0800567 if (mountMode != VoldNativeService::REMOUNT_MODE_INSTALLER) {
568 mountPkgSpecificDir(mntSource, mntTarget, package, "obb");
569 }
570 }
571 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800572 if (BindMount(obbSourceDir, obbTargetDir) < 0) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800573 continue;
574 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700575 }
576 }
577 _exit(0);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700578 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700579
580 if (child == -1) {
581 PLOG(ERROR) << "Failed to fork";
582 } else {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800583 childPids.push_back(child);
Sudheer Shanka53947a32018-08-01 10:24:13 -0700584 }
585 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800586 for (auto& child : childPids) {
587 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
588 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700589 return 0;
590}
591
Sudheer Shanka03992e32018-12-12 12:43:38 -0800592int VolumeManager::getMountModeForRunningProc(const std::vector<std::string>& packagesForUid,
Sudheer Shanka55049012019-01-09 12:15:15 -0800593 userid_t userId, struct stat& mntWriteStat,
594 struct stat& mntFullStat) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800595 struct stat storageSb;
596 if (TEMP_FAILURE_RETRY(stat("/storage", &storageSb)) == -1) {
597 PLOG(ERROR) << "Failed to stat /storage";
598 return -1;
599 }
600
601 // Some packages have access to full external storage, identify processes belonging
Sudheer Shanka55049012019-01-09 12:15:15 -0800602 // to those packages by comparing inode no.s of /mnt/runtime/full and /storage
603 if (storageSb.st_dev == mntFullStat.st_dev && storageSb.st_ino == mntFullStat.st_ino) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800604 return VoldNativeService::REMOUNT_MODE_FULL;
Sudheer Shanka55049012019-01-09 12:15:15 -0800605 } else if (storageSb.st_dev == mntWriteStat.st_dev && storageSb.st_ino == mntWriteStat.st_ino) {
606 return VoldNativeService::REMOUNT_MODE_LEGACY;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800607 }
608
609 std::string obbMountFile =
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800610 StringPrintf("/mnt/user/%d/obb_mount/%s", userId, packagesForUid[0].c_str());
611 if (TEMP_FAILURE_RETRY(access(obbMountFile.c_str(), F_OK)) != -1) {
Sudheer Shanka03992e32018-12-12 12:43:38 -0800612 return VoldNativeService::REMOUNT_MODE_INSTALLER;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800613 } else if (errno != ENOENT) {
614 PLOG(ERROR) << "Failed to access " << obbMountFile;
615 return -1;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800616 }
617
618 // Some packages don't have access to external storage and processes belonging to
619 // those packages don't have anything mounted at /storage. So, identify those
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800620 // processes by comparing inode no.s of /mnt/user/%d/package
Sudheer Shanka03992e32018-12-12 12:43:38 -0800621 // and /storage
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800622 std::string sandbox = StringPrintf("/mnt/user/%d/package", userId);
623 struct stat sandboxStat;
624 if (TEMP_FAILURE_RETRY(stat(sandbox.c_str(), &sandboxStat)) == -1) {
625 PLOG(ERROR) << "Failed to stat " << sandbox;
626 return -1;
627 }
628 if (storageSb.st_dev == sandboxStat.st_dev && storageSb.st_ino == sandboxStat.st_ino) {
629 return VoldNativeService::REMOUNT_MODE_WRITE;
630 }
631
632 return VoldNativeService::REMOUNT_MODE_NONE;
633}
634
635int VolumeManager::handleMountModeInstaller(int mountMode, int obbMountDirFd,
636 const std::string& obbMountDir,
637 const std::string& sandboxId) {
638 if (mountMode == VoldNativeService::REMOUNT_MODE_INSTALLER) {
639 if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
640 return 0;
641 } else if (errno != ENOENT) {
642 PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
643 return -errno;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800644 }
Nick Kralevich58e1a812019-03-29 18:35:22 -0700645 const unique_fd fd(TEMP_FAILURE_RETRY(
646 openat(obbMountDirFd, sandboxId.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600)));
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800647 if (fd.get() < 0) {
648 PLOG(ERROR) << "Failed to create " << obbMountDir << "/" << sandboxId;
649 return -errno;
650 }
651 } else {
652 if (TEMP_FAILURE_RETRY(faccessat(obbMountDirFd, sandboxId.c_str(), F_OK, 0)) != -1) {
653 if (TEMP_FAILURE_RETRY(unlinkat(obbMountDirFd, sandboxId.c_str(), 0)) == -1) {
654 PLOG(ERROR) << "Failed to unlink " << obbMountDir << "/" << sandboxId;
655 return -errno;
656 }
657 } else if (errno != ENOENT) {
658 PLOG(ERROR) << "Failed to access " << obbMountDir << "/" << sandboxId;
659 return -errno;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800660 }
661 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800662 return 0;
Sudheer Shanka03992e32018-12-12 12:43:38 -0800663}
664
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700665int VolumeManager::prepareSandboxes(userid_t userId, const std::vector<std::string>& packageNames,
666 const std::vector<std::string>& visibleVolLabels) {
667 if (visibleVolLabels.empty()) {
668 return 0;
669 }
670 for (auto& volumeLabel : visibleVolLabels) {
671 std::string volumeRoot(StringPrintf("/mnt/runtime/write/%s", volumeLabel.c_str()));
672 bool isVolPrimaryEmulated = (volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated());
673 if (isVolPrimaryEmulated) {
674 StringAppendF(&volumeRoot, "/%d", userId);
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000675 if (CreateDir(volumeRoot, 0755) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700676 return -errno;
677 }
678 }
679
680 std::string sandboxRoot =
681 prepareSubDirs(volumeRoot, "Android/sandbox/", 0700, AID_ROOT, AID_ROOT);
682 if (sandboxRoot.empty()) {
683 return -errno;
684 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700685 }
Sudheer Shanka83680402019-02-24 10:16:09 -0800686
687 if (prepareSandboxTargets(userId, visibleVolLabels) < 0) {
688 return -errno;
689 }
690
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800691 if (mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, -1) < 0) {
692 PLOG(ERROR) << "Failed to setup sandboxes for already running processes";
693 return -errno;
694 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700695 return 0;
696}
697
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000698int VolumeManager::prepareSandboxTargets(userid_t userId,
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000699 const std::vector<std::string>& visibleVolLabels) {
700 std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
701 if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800702 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000703 return -errno;
704 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800705
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000706 StringAppendF(&mntTargetRoot, "/package");
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800707 if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
708 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000709 return -errno;
710 }
711
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800712 for (auto& volumeLabel : visibleVolLabels) {
713 std::string sandboxTarget =
714 StringPrintf("%s/%s", mntTargetRoot.c_str(), volumeLabel.c_str());
715 if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
716 PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
717 return -errno;
718 }
719
720 if (mPrimary && volumeLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
721 StringAppendF(&sandboxTarget, "/%d", userId);
722 if (fs_prepare_dir(sandboxTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
723 PLOG(ERROR) << "Failed to fs_prepare_dir " << sandboxTarget;
724 return -errno;
725 }
726 }
727 }
728
729 StringAppendF(&mntTargetRoot, "/self");
730 if (fs_prepare_dir(mntTargetRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
731 PLOG(ERROR) << "Failed to fs_prepare_dir " << mntTargetRoot;
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000732 return -errno;
733 }
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000734
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000735 if (mPrimary) {
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800736 std::string pkgPrimarySource(mPrimary->getPath());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000737 if (mPrimary->isEmulated()) {
738 StringAppendF(&pkgPrimarySource, "/%d", userId);
739 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800740 StringAppendF(&mntTargetRoot, "/primary");
741 if (Symlink(pkgPrimarySource, mntTargetRoot) < 0) {
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000742 return -errno;
743 }
744 }
745 return 0;
746}
747
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700748std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
749 mode_t mode, uid_t uid, gid_t gid) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700750 std::string path(pathPrefix);
751 std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
752 for (size_t i = 0; i < subDirList.size(); ++i) {
753 std::string subDir = subDirList[i];
754 if (subDir.empty()) {
755 continue;
756 }
757 StringAppendF(&path, "/%s", subDir.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000758 if (CreateDir(path, mode) < 0) {
Sudheer Shanka53947a32018-08-01 10:24:13 -0700759 return kEmptyString;
760 }
761 }
762 return path;
763}
764
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700765bool VolumeManager::createPkgSpecificDirRoots(const std::string& volumeRoot) {
766 std::string volumeAndroidRoot = StringPrintf("%s/Android", volumeRoot.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000767 if (CreateDir(volumeAndroidRoot, 0700) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700768 return false;
769 }
770 std::array<std::string, 3> dirs = {"data", "media", "obb"};
771 for (auto& dir : dirs) {
772 std::string path = StringPrintf("%s/%s", volumeAndroidRoot.c_str(), dir.c_str());
Sudheer Shankaf9b38a52019-02-14 19:09:51 +0000773 if (CreateDir(path, 0700) < 0) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700774 return false;
775 }
776 }
777 return true;
Sudheer Shanka53947a32018-08-01 10:24:13 -0700778}
779
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700780int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
781 mAddedUsers[userId] = userSerialNumber;
782 return 0;
783}
784
785int VolumeManager::onUserRemoved(userid_t userId) {
786 mAddedUsers.erase(userId);
787 return 0;
788}
789
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700790int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames,
791 const std::vector<int>& appIds,
792 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700793 LOG(VERBOSE) << "onUserStarted: " << userId;
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700794 // Note that sometimes the system will spin up processes from Zygote
795 // before actually starting the user, so we're okay if Zygote
796 // already created this directory.
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -0600797 std::string path(StringPrintf("%s/%d", kPathUserMount, userId));
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700798 fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
799
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700800 mStartedUsers.insert(userId);
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700801 mUserPackages[userId] = packageNames;
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700802 for (size_t i = 0; i < packageNames.size(); ++i) {
803 mAppIds[packageNames[i]] = appIds[i];
804 mSandboxIds[appIds[i]] = sandboxIds[i];
805 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700806 if (mPrimary) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700807 linkPrimary(userId);
808 }
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800809 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700810 std::vector<std::string> visibleVolLabels;
811 for (auto& volId : mVisibleVolumeIds) {
812 auto vol = findVolume(volId);
813 userid_t mountUserId = vol->getMountUserId();
814 if (mountUserId == userId || vol->isEmulated()) {
815 visibleVolLabels.push_back(vol->getLabel());
816 }
817 }
818 if (prepareSandboxes(userId, packageNames, visibleVolLabels) != 0) {
819 return -errno;
820 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700821 }
822 return 0;
823}
824
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700825int VolumeManager::onUserStopped(userid_t userId) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700826 LOG(VERBOSE) << "onUserStopped: " << userId;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -0700827 mStartedUsers.erase(userId);
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700828
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800829 if (hasIsolatedStorage()) {
Sudheer Shanka023b5392019-02-06 12:39:19 -0800830 auto& userPackages = mUserPackages[userId];
831 std::string userMntTargetRoot = StringPrintf("/mnt/user/%d", userId);
Sudheer Shanka727c5fa2019-02-21 15:00:11 -0800832 std::string pkgPrimaryDir =
833 StringPrintf("%s/package/self/primary", userMntTargetRoot.c_str());
834 if (Unlink(pkgPrimaryDir) < 0) {
835 return -errno;
Sudheer Shanka023b5392019-02-06 12:39:19 -0800836 }
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700837 mUserPackages.erase(userId);
Sudheer Shanka023b5392019-02-06 12:39:19 -0800838 if (DeleteDirContentsAndDir(userMntTargetRoot) < 0) {
839 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << userMntTargetRoot;
Sudheer Shanka9acc6d42018-10-06 19:03:02 -0700840 return -errno;
841 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800842 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << userMntTargetRoot;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700843 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -0700844 return 0;
845}
846
Sudheer Shankad484aa92018-07-31 10:07:34 -0700847int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700848 const std::vector<int32_t>& appIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700849 for (size_t i = 0; i < packageNames.size(); ++i) {
850 mAppIds[packageNames[i]] = appIds[i];
851 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700852 return 0;
853}
854
855int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -0700856 const std::vector<std::string>& sandboxIds) {
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -0700857 for (size_t i = 0; i < appIds.size(); ++i) {
858 mSandboxIds[appIds[i]] = sandboxIds[i];
859 }
Sudheer Shankad484aa92018-07-31 10:07:34 -0700860 return 0;
861}
862
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700863int VolumeManager::prepareSandboxForApp(const std::string& packageName, appid_t appId,
864 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800865 if (!hasIsolatedStorage()) {
Sudheer Shankac7562092018-08-24 10:20:56 -0700866 return 0;
867 } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
868 // User not started, no need to do anything now. Required bind mounts for the package will
869 // be created when the user starts.
870 return 0;
871 }
Sudheer Shanka23d725d2019-02-28 10:46:48 -0800872
873 auto& userPackages = mUserPackages[userId];
874 if (std::find(userPackages.begin(), userPackages.end(), packageName) != userPackages.end()) {
875 return 0;
876 }
877
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700878 LOG(VERBOSE) << "prepareSandboxForApp: " << packageName << ", appId=" << appId
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700879 << ", sandboxId=" << sandboxId << ", userId=" << userId;
Sudheer Shankac7562092018-08-24 10:20:56 -0700880 mUserPackages[userId].push_back(packageName);
881 mAppIds[packageName] = appId;
882 mSandboxIds[appId] = sandboxId;
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700883
884 std::vector<std::string> visibleVolLabels;
885 for (auto& volId : mVisibleVolumeIds) {
886 auto vol = findVolume(volId);
887 userid_t mountUserId = vol->getMountUserId();
888 if (mountUserId == userId || vol->isEmulated()) {
889 visibleVolLabels.push_back(vol->getLabel());
890 }
Sudheer Shankac7562092018-08-24 10:20:56 -0700891 }
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700892 return prepareSandboxes(userId, {packageName}, visibleVolLabels);
Sudheer Shankac7562092018-08-24 10:20:56 -0700893}
894
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700895int VolumeManager::destroySandboxForApp(const std::string& packageName,
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700896 const std::string& sandboxId, userid_t userId) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800897 if (!hasIsolatedStorage()) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700898 return 0;
899 }
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700900 LOG(VERBOSE) << "destroySandboxForApp: " << packageName << ", sandboxId=" << sandboxId
901 << ", userId=" << userId;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700902 auto& userPackages = mUserPackages[userId];
Sudheer Shankaba0c62f2018-12-16 18:22:34 -0800903 userPackages.erase(std::remove(userPackages.begin(), userPackages.end(), packageName),
904 userPackages.end());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700905 // If the package is not uninstalled in any other users, remove appId and sandboxId
906 // corresponding to it from the internal state.
907 bool installedInAnyUser = false;
908 for (auto& it : mUserPackages) {
909 auto& packages = it.second;
910 if (std::find(packages.begin(), packages.end(), packageName) != packages.end()) {
911 installedInAnyUser = true;
912 break;
913 }
914 }
915 if (!installedInAnyUser) {
Sudheer Shanka69bc40f2018-10-25 11:06:55 -0700916 const auto& entry = mAppIds.find(packageName);
917 if (entry != mAppIds.end()) {
918 mSandboxIds.erase(entry->second);
919 mAppIds.erase(entry);
920 }
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700921 }
922
923 std::vector<std::string> visibleVolLabels;
924 for (auto& volId : mVisibleVolumeIds) {
925 auto vol = findVolume(volId);
926 userid_t mountUserId = vol->getMountUserId();
927 if (mountUserId == userId || vol->isEmulated()) {
928 if (destroySandboxForAppOnVol(packageName, sandboxId, userId, vol->getLabel()) < 0) {
929 return -errno;
930 }
931 }
932 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800933
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700934 return 0;
935}
936
937int VolumeManager::destroySandboxForAppOnVol(const std::string& packageName,
938 const std::string& sandboxId, userid_t userId,
939 const std::string& volLabel) {
940 LOG(VERBOSE) << "destroySandboxOnVol: " << packageName << ", userId=" << userId
941 << ", volLabel=" << volLabel;
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700942
943 std::string sandboxDir = StringPrintf("/mnt/runtime/write/%s", volLabel.c_str());
944 if (volLabel == mPrimary->getLabel() && mPrimary->isEmulated()) {
945 StringAppendF(&sandboxDir, "/%d", userId);
946 }
Sudheer Shanka51a38da2018-10-18 08:51:31 -0700947 StringAppendF(&sandboxDir, "/Android/sandbox/%s", sandboxId.c_str());
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700948
Sudheer Shanka023b5392019-02-06 12:39:19 -0800949 if (DeleteDirContentsAndDir(sandboxDir) < 0) {
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700950 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << sandboxDir;
951 return -errno;
952 }
Sudheer Shanka023b5392019-02-06 12:39:19 -0800953
Sudheer Shankafa6a1742018-10-04 16:26:22 -0700954 return 0;
955}
956
Jeff Sharkey401b2602017-12-14 22:15:20 -0700957int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
958 mSecureKeyguardShowing = isShowing;
959 if (!mSecureKeyguardShowing) {
960 // Now that secure keyguard has been dismissed, process
961 // any pending disks
962 for (const auto& disk : mPendingDisks) {
963 disk->create();
964 mDisks.push_back(disk);
965 }
966 mPendingDisks.clear();
967 }
968 return 0;
969}
970
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700971int VolumeManager::onVolumeMounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -0800972 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -0700973 return 0;
974 }
975
976 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_VISIBLE) == 0) {
977 return 0;
978 }
979
980 mVisibleVolumeIds.insert(vol->getId());
981 userid_t mountUserId = vol->getMountUserId();
982 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
983 // We don't want to create another shared_ptr here because then we will end up with
984 // two shared_ptrs owning the underlying pointer without sharing it.
985 mPrimary = findVolume(vol->getId());
986 for (userid_t userId : mStartedUsers) {
987 if (linkPrimary(userId) != 0) {
988 return -errno;
989 }
990 }
991 }
992 if (vol->isEmulated()) {
993 for (userid_t userId : mStartedUsers) {
994 if (prepareSandboxes(userId, mUserPackages[userId], {vol->getLabel()}) != 0) {
995 return -errno;
996 }
997 }
998 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
999 if (prepareSandboxes(mountUserId, mUserPackages[mountUserId], {vol->getLabel()}) != 0) {
1000 return -errno;
1001 }
1002 }
1003 return 0;
1004}
1005
1006int VolumeManager::onVolumeUnmounted(android::vold::VolumeBase* vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001007 if (!hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001008 return 0;
1009 }
1010
1011 if (mVisibleVolumeIds.erase(vol->getId()) == 0) {
1012 return 0;
1013 }
1014
1015 if ((vol->getMountFlags() & android::vold::VoldNativeService::MOUNT_FLAG_PRIMARY) != 0) {
1016 mPrimary = nullptr;
1017 }
1018
1019 LOG(VERBOSE) << "visibleVolumeUnmounted: " << vol;
1020 userid_t mountUserId = vol->getMountUserId();
1021 if (vol->isEmulated()) {
1022 for (userid_t userId : mStartedUsers) {
1023 if (destroySandboxesForVol(vol, userId) != 0) {
1024 return -errno;
1025 }
1026 }
1027 } else if (mStartedUsers.find(mountUserId) != mStartedUsers.end()) {
1028 if (destroySandboxesForVol(vol, mountUserId) != 0) {
1029 return -errno;
1030 }
1031 }
1032 return 0;
1033}
1034
1035int VolumeManager::destroySandboxesForVol(android::vold::VolumeBase* vol, userid_t userId) {
1036 LOG(VERBOSE) << "destroysandboxesForVol: " << vol << " for user=" << userId;
Sudheer Shanka727c5fa2019-02-21 15:00:11 -08001037 std::string volSandboxRoot =
1038 StringPrintf("/mnt/user/%d/package/%s", userId, vol->getLabel().c_str());
1039 if (android::vold::DeleteDirContentsAndDir(volSandboxRoot) < 0) {
1040 PLOG(ERROR) << "DeleteDirContentsAndDir failed on " << volSandboxRoot;
1041 return -errno;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001042 }
Sudheer Shanka727c5fa2019-02-21 15:00:11 -08001043 LOG(VERBOSE) << "Success: DeleteDirContentsAndDir on " << volSandboxRoot;
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001044 return 0;
1045}
1046
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001047int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001048 if (hasIsolatedStorage()) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001049 return 0;
1050 }
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001051 mPrimary = vol;
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001052 for (userid_t userId : mStartedUsers) {
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001053 linkPrimary(userId);
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001054 }
1055 return 0;
1056}
1057
Sudheer Shanka817b9112018-12-13 17:40:28 -08001058int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
Sudheer Shanka34b437b2019-01-17 17:20:47 -08001059 if (!hasIsolatedStorage()) {
Sudheer Shanka817b9112018-12-13 17:40:28 -08001060 return remountUidLegacy(uid, mountMode);
1061 }
1062
1063 appid_t appId = multiuser_get_app_id(uid);
1064 userid_t userId = multiuser_get_user_id(uid);
1065 std::vector<std::string> visibleVolLabels;
1066 for (auto& volId : mVisibleVolumeIds) {
1067 auto vol = findVolume(volId);
1068 userid_t mountUserId = vol->getMountUserId();
1069 if (mountUserId == userId || vol->isEmulated()) {
1070 visibleVolLabels.push_back(vol->getLabel());
1071 }
1072 }
1073
1074 // Finding one package with appId is enough
1075 std::vector<std::string> packageNames;
1076 for (auto it = mAppIds.begin(); it != mAppIds.end(); ++it) {
1077 if (it->second == appId) {
1078 packageNames.push_back(it->first);
1079 break;
1080 }
1081 }
1082 if (packageNames.empty()) {
1083 PLOG(ERROR) << "Failed to find packageName for " << uid;
Sudheer Shanka53947a32018-08-01 10:24:13 -07001084 return -1;
1085 }
Sudheer Shanka817b9112018-12-13 17:40:28 -08001086 return mountPkgSpecificDirsForRunningProcs(userId, packageNames, visibleVolLabels, mountMode);
1087}
1088
1089int VolumeManager::remountUidLegacy(uid_t uid, int32_t mountMode) {
1090 std::string mode;
1091 switch (mountMode) {
1092 case VoldNativeService::REMOUNT_MODE_NONE:
1093 mode = "none";
1094 break;
1095 case VoldNativeService::REMOUNT_MODE_DEFAULT:
1096 mode = "default";
1097 break;
1098 case VoldNativeService::REMOUNT_MODE_READ:
1099 mode = "read";
1100 break;
1101 case VoldNativeService::REMOUNT_MODE_WRITE:
Sudheer Shankaa05ea742019-04-12 13:55:28 -07001102 case VoldNativeService::REMOUNT_MODE_LEGACY:
1103 case VoldNativeService::REMOUNT_MODE_INSTALLER:
Sudheer Shanka817b9112018-12-13 17:40:28 -08001104 mode = "write";
1105 break;
Sudheer Shanka36bdf7a2019-04-18 15:18:30 -07001106 case VoldNativeService::REMOUNT_MODE_FULL:
1107 mode = "full";
1108 break;
Sudheer Shanka817b9112018-12-13 17:40:28 -08001109 default:
1110 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
1111 return -1;
1112 }
Jeff Sharkey66270a22015-06-24 11:49:24 -07001113 LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
1114
1115 DIR* dir;
1116 struct dirent* de;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001117 std::string rootName;
1118 std::string pidName;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001119 int pidFd;
1120 int nsFd;
1121 struct stat sb;
1122 pid_t child;
1123
Jiyong Park8d21c922019-01-04 13:35:25 +09001124 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
1125
Jeff Sharkey66270a22015-06-24 11:49:24 -07001126 if (!(dir = opendir("/proc"))) {
1127 PLOG(ERROR) << "Failed to opendir";
1128 return -1;
1129 }
1130
1131 // Figure out root namespace to compare against below
Jeff Sharkey3472e522017-10-06 18:02:53 -06001132 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
1133 PLOG(ERROR) << "Failed to read root namespace";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001134 closedir(dir);
1135 return -1;
1136 }
1137
1138 // Poke through all running PIDs look for apps running as UID
1139 while ((de = readdir(dir))) {
Jeff Vander Stoep58890832017-10-23 17:12:31 -07001140 pid_t pid;
1141 if (de->d_type != DT_DIR) continue;
1142 if (!android::base::ParseInt(de->d_name, &pid)) continue;
1143
Jeff Sharkey66270a22015-06-24 11:49:24 -07001144 pidFd = -1;
1145 nsFd = -1;
1146
1147 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1148 if (pidFd < 0) {
1149 goto next;
1150 }
1151 if (fstat(pidFd, &sb) != 0) {
1152 PLOG(WARNING) << "Failed to stat " << de->d_name;
1153 goto next;
1154 }
1155 if (sb.st_uid != uid) {
1156 goto next;
1157 }
1158
1159 // Matches so far, but refuse to touch if in root namespace
1160 LOG(DEBUG) << "Found matching PID " << de->d_name;
Jeff Sharkey3472e522017-10-06 18:02:53 -06001161 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001162 PLOG(WARNING) << "Failed to read namespace for " << de->d_name;
1163 goto next;
1164 }
Jeff Sharkey3472e522017-10-06 18:02:53 -06001165 if (rootName == pidName) {
Jeff Sharkey66270a22015-06-24 11:49:24 -07001166 LOG(WARNING) << "Skipping due to root namespace";
1167 goto next;
1168 }
1169
Jiyong Park8d21c922019-01-04 13:35:25 +09001170 if (apexUpdatable) {
1171 std::string exeName;
1172 // When ro.apex.bionic_updatable is set to true,
1173 // some early native processes have mount namespaces that are different
1174 // from that of the init. Therefore, above check can't filter them out.
1175 // Since the propagation type of / is 'shared', unmounting /storage
1176 // for the early native processes affects other processes including
1177 // init. Filter out such processes by skipping if a process is a
1178 // non-Java process whose UID is < AID_APP_START. (The UID condition
1179 // is required to not filter out child processes spawned by apps.)
1180 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
1181 PLOG(WARNING) << "Failed to read exe name for " << de->d_name;
1182 goto next;
1183 }
1184 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
1185 LOG(WARNING) << "Skipping due to native system process";
1186 goto next;
1187 }
1188 }
1189
Jeff Sharkey66270a22015-06-24 11:49:24 -07001190 // We purposefully leave the namespace open across the fork
Nick Kraleviche7e89ac2019-03-29 16:03:51 -07001191 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
1192 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001193 if (nsFd < 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001194 PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001195 goto next;
1196 }
1197
1198 if (!(child = fork())) {
1199 if (setns(nsFd, CLONE_NEWNS) != 0) {
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001200 PLOG(ERROR) << "Failed to setns for " << de->d_name;
Jeff Sharkey66270a22015-06-24 11:49:24 -07001201 _exit(1);
1202 }
1203
Sudheer Shanka99d304a2018-09-27 14:53:51 -07001204 android::vold::UnmountTree("/storage/");
Jeff Sharkey66270a22015-06-24 11:49:24 -07001205
1206 std::string storageSource;
1207 if (mode == "default") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001208 storageSource = "/mnt/runtime/default";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001209 } else if (mode == "read") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001210 storageSource = "/mnt/runtime/read";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001211 } else if (mode == "write") {
Jeff Sharkey1bd078f2015-08-06 11:40:00 -07001212 storageSource = "/mnt/runtime/write";
Jeff Sharkey66270a22015-06-24 11:49:24 -07001213 } else {
1214 // Sane default of no storage visible
1215 _exit(0);
1216 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001217 if (TEMP_FAILURE_RETRY(
1218 mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
1219 PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001220 _exit(1);
Jeff Sharkey66270a22015-06-24 11:49:24 -07001221 }
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001222 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
1223 PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
Hidehiko Abe674bed12016-03-09 16:42:10 +09001224 _exit(1);
1225 }
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001226
1227 // Mount user-specific symlink helper into place
1228 userid_t user_id = multiuser_get_user_id(uid);
1229 std::string userSource(StringPrintf("/mnt/user/%d", user_id));
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001230 if (TEMP_FAILURE_RETRY(
1231 mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
1232 PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
Jeff Sharkeyc7b5b572015-06-30 15:54:17 -07001233 _exit(1);
1234 }
1235
Jeff Sharkey66270a22015-06-24 11:49:24 -07001236 _exit(0);
1237 }
1238
1239 if (child == -1) {
1240 PLOG(ERROR) << "Failed to fork";
1241 goto next;
1242 } else {
1243 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
1244 }
1245
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001246 next:
Jeff Sharkey66270a22015-06-24 11:49:24 -07001247 close(nsFd);
1248 close(pidFd);
1249 }
1250 closedir(dir);
1251 return 0;
1252}
1253
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001254int VolumeManager::reset() {
1255 // Tear down all existing disks/volumes and start from a blank slate so
1256 // newly connected framework hears all events.
Gao Xiangd263da82017-08-14 11:32:13 +08001257 if (mInternalEmulated != nullptr) {
1258 mInternalEmulated->destroy();
1259 mInternalEmulated->create();
1260 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001261 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001262 disk->destroy();
1263 disk->create();
1264 }
Jeff Sharkeyfa1c6772017-03-25 22:49:13 -06001265 updateVirtualDisk();
Jeff Sharkeybd3038d2015-06-10 09:42:01 -07001266 mAddedUsers.clear();
Sudheer Shanka62bbb2b2018-08-01 01:09:10 -07001267
1268 mUserPackages.clear();
1269 mAppIds.clear();
1270 mSandboxIds.clear();
Sudheer Shanka40ab6742018-09-18 13:07:45 -07001271 mVisibleVolumeIds.clear();
Sudheer Shanka3a7ee5c2018-08-07 17:10:11 -07001272
Sudheer Shanka023b5392019-02-06 12:39:19 -08001273 for (userid_t userId : mStartedUsers) {
Sudheer Shanka30df1c62019-02-22 17:03:02 -08001274 DeleteDirContents(StringPrintf("/mnt/user/%d/package", userId));
Sudheer Shanka023b5392019-02-06 12:39:19 -08001275 }
1276 mStartedUsers.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001277 return 0;
1278}
1279
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001280// Can be called twice (sequentially) during shutdown. should be safe for that.
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001281int VolumeManager::shutdown() {
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001282 if (mInternalEmulated == nullptr) {
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001283 return 0; // already shutdown
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001284 }
Paul Crowley56292ef2017-10-20 08:07:53 -07001285 android::vold::sSleepOnUnmount = false;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001286 mInternalEmulated->destroy();
Keun-young Parka5bbb5e2017-03-13 18:02:50 -07001287 mInternalEmulated = nullptr;
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001288 for (const auto& disk : mDisks) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001289 disk->destroy();
1290 }
Risan8c9f3322018-10-29 08:52:56 +09001291 mStubVolumes.clear();
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001292 mDisks.clear();
Jeff Sharkey401b2602017-12-14 22:15:20 -07001293 mPendingDisks.clear();
Paul Crowley56292ef2017-10-20 08:07:53 -07001294 android::vold::sSleepOnUnmount = true;
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001295 return 0;
San Mehatf1b736b2009-10-10 17:22:08 -07001296}
1297
Jeff Sharkey9c484982015-03-31 10:35:33 -07001298int VolumeManager::unmountAll() {
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001299 std::lock_guard<std::mutex> lock(mLock);
Jeff Sharkey67b8c492017-09-21 17:08:43 -06001300 ATRACE_NAME("VolumeManager::unmountAll()");
Jeff Sharkeyc8e04c52015-04-21 12:14:17 -07001301
Jeff Sharkey9c484982015-03-31 10:35:33 -07001302 // First, try gracefully unmounting all known devices
1303 if (mInternalEmulated != nullptr) {
1304 mInternalEmulated->unmount();
1305 }
Risan8c9f3322018-10-29 08:52:56 +09001306 for (const auto& stub : mStubVolumes) {
1307 stub->unmount();
1308 }
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001309 for (const auto& disk : mDisks) {
Jeff Sharkey9c484982015-03-31 10:35:33 -07001310 disk->unmountAll();
1311 }
1312
1313 // Worst case we might have some stale mounts lurking around, so
1314 // force unmount those just to be safe.
LongPing.WEI4f046062018-11-23 19:27:35 +08001315 FILE* fp = setmntent("/proc/mounts", "re");
Jeff Sharkey9c484982015-03-31 10:35:33 -07001316 if (fp == NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001317 PLOG(ERROR) << "Failed to open /proc/mounts";
Jeff Sharkey9c484982015-03-31 10:35:33 -07001318 return -errno;
1319 }
1320
1321 // Some volumes can be stacked on each other, so force unmount in
1322 // reverse order to give us the best chance of success.
1323 std::list<std::string> toUnmount;
1324 mntent* mentry;
1325 while ((mentry = getmntent(fp)) != NULL) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001326 auto test = std::string(mentry->mnt_dir);
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001327 if ((StartsWith(test, "/mnt/") &&
1328#ifdef __ANDROID_DEBUGGABLE__
1329 !StartsWith(test, "/mnt/scratch") &&
1330#endif
1331 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product")) ||
1332 StartsWith(test, "/storage/")) {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001333 toUnmount.push_front(test);
Jeff Sharkey9c484982015-03-31 10:35:33 -07001334 }
1335 }
1336 endmntent(fp);
1337
Chih-Hung Hsieh11a2ce82016-07-27 14:11:02 -07001338 for (const auto& path : toUnmount) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001339 LOG(DEBUG) << "Tearing down stale mount " << path;
Jeff Sharkey9c484982015-03-31 10:35:33 -07001340 android::vold::ForceUnmount(path);
1341 }
1342
1343 return 0;
1344}
1345
Jeff Sharkey3472e522017-10-06 18:02:53 -06001346int VolumeManager::mkdirs(const std::string& path) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001347 // Only offer to create directories for paths managed by vold
Mark Salyzyn86e81e72018-09-20 10:09:27 -07001348 if (StartsWith(path, "/storage/")) {
Jeff Sharkey36801cc2015-03-13 16:09:20 -07001349 // fs_mkdirs() does symlink checking and relative path enforcement
Jeff Sharkey3472e522017-10-06 18:02:53 -06001350 return fs_mkdirs(path.c_str(), 0700);
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001351 } else {
Jeff Sharkey3472e522017-10-06 18:02:53 -06001352 LOG(ERROR) << "Failed to find mounted volume for " << path;
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001353 return -EINVAL;
1354 }
Jeff Sharkey71ebe152013-09-17 17:24:38 -07001355}
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001356
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001357int VolumeManager::createObb(const std::string& sourcePath, const std::string& sourceKey,
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001358 int32_t ownerGid, std::string* outVolId) {
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001359 int id = mNextObbId++;
1360
1361 auto vol = std::shared_ptr<android::vold::VolumeBase>(
Paul Crowleyedf7a4e2018-09-18 15:14:18 -07001362 new android::vold::ObbVolume(id, sourcePath, sourceKey, ownerGid));
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001363 vol->create();
1364
1365 mObbVolumes.push_back(vol);
1366 *outVolId = vol->getId();
1367 return android::OK;
1368}
1369
1370int VolumeManager::destroyObb(const std::string& volId) {
1371 auto i = mObbVolumes.begin();
1372 while (i != mObbVolumes.end()) {
1373 if ((*i)->getId() == volId) {
1374 (*i)->destroy();
1375 i = mObbVolumes.erase(i);
1376 } else {
1377 ++i;
1378 }
1379 }
1380 return android::OK;
1381}
1382
Risan8c9f3322018-10-29 08:52:56 +09001383int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1384 const std::string& fsType, const std::string& fsUuid,
1385 const std::string& fsLabel, std::string* outVolId) {
1386 int id = mNextStubVolumeId++;
1387 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1388 new android::vold::StubVolume(id, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1389 vol->create();
1390
1391 mStubVolumes.push_back(vol);
1392 *outVolId = vol->getId();
1393 return android::OK;
1394}
1395
1396int VolumeManager::destroyStubVolume(const std::string& volId) {
1397 auto i = mStubVolumes.begin();
1398 while (i != mStubVolumes.end()) {
1399 if ((*i)->getId() == volId) {
1400 (*i)->destroy();
1401 i = mStubVolumes.erase(i);
1402 } else {
1403 ++i;
1404 }
1405 }
1406 return android::OK;
1407}
1408
Risan8f6198d2018-10-26 20:56:45 -06001409int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
Risanac02a482018-10-31 21:59:47 -06001410 return android::vold::MountAppFuse(uid, mountId, device_fd);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001411}
1412
Risan8f6198d2018-10-26 20:56:45 -06001413int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
Risanac02a482018-10-31 21:59:47 -06001414 return android::vold::UnmountAppFuse(uid, mountId);
Risan8f6198d2018-10-26 20:56:45 -06001415}
1416
1417int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
Risanac02a482018-10-31 21:59:47 -06001418 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
Jeff Sharkey11c2d382017-09-11 10:32:01 -06001419}