1 /*
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
17 #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <limits.h>
23 #include <mntent.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/ioctl.h>
28 #include <sys/mount.h>
29 #include <sys/stat.h>
30 #include <sys/sysmacros.h>
31 #include <sys/types.h>
32 #include <sys/wait.h>
33 #include <unistd.h>
34 #include <array>
35
36 #include <linux/kdev_t.h>
37
38 #include <ApexProperties.sysprop.h>
39 #include <android-base/logging.h>
40 #include <android-base/parseint.h>
41 #include <android-base/properties.h>
42 #include <android-base/stringprintf.h>
43 #include <android-base/strings.h>
44 #include <async_safe/log.h>
45
46 #include <cutils/fs.h>
47 #include <utils/Trace.h>
48
49 #include <selinux/android.h>
50
51 #include <sysutils/NetlinkEvent.h>
52
53 #include <private/android_filesystem_config.h>
54
55 #include <fscrypt/fscrypt.h>
56
57 #include "AppFuseUtil.h"
58 #include "FsCrypt.h"
59 #include "Loop.h"
60 #include "NetlinkManager.h"
61 #include "Process.h"
62 #include "Utils.h"
63 #include "VoldNativeService.h"
64 #include "VoldUtil.h"
65 #include "VolumeManager.h"
66 #include "fs/Ext4.h"
67 #include "fs/Vfat.h"
68 #include "model/EmulatedVolume.h"
69 #include "model/ObbVolume.h"
70 #include "model/PrivateVolume.h"
71 #include "model/StubVolume.h"
72
73 using android::OK;
74 using android::base::GetBoolProperty;
75 using android::base::StartsWith;
76 using android::base::StringAppendF;
77 using android::base::StringPrintf;
78 using android::base::unique_fd;
79 using android::vold::BindMount;
80 using android::vold::CreateDir;
81 using android::vold::DeleteDirContents;
82 using android::vold::DeleteDirContentsAndDir;
83 using android::vold::EnsureDirExists;
84 using android::vold::IsFilesystemSupported;
85 using android::vold::IsSdcardfsUsed;
86 using android::vold::IsVirtioBlkDevice;
87 using android::vold::PrepareAndroidDirs;
88 using android::vold::PrepareAppDirFromRoot;
89 using android::vold::PrivateVolume;
90 using android::vold::Symlink;
91 using android::vold::Unlink;
92 using android::vold::UnmountTree;
93 using android::vold::VoldNativeService;
94 using android::vold::VolumeBase;
95
96 static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
97
98 static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
99
100 static const std::string kEmptyString("");
101
102 /* 512MiB is large enough for testing purposes */
103 static const unsigned int kSizeVirtualDisk = 536870912;
104
105 static const unsigned int kMajorBlockMmc = 179;
106
107 using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
108
109 VolumeManager* VolumeManager::sInstance = NULL;
110
Instance()111 VolumeManager* VolumeManager::Instance() {
112 if (!sInstance) sInstance = new VolumeManager();
113 return sInstance;
114 }
115
VolumeManager()116 VolumeManager::VolumeManager() {
117 mDebug = false;
118 mNextObbId = 0;
119 mNextStubId = 0;
120 // For security reasons, assume that a secure keyguard is
121 // showing until we hear otherwise
122 mSecureKeyguardShowing = true;
123 }
124
~VolumeManager()125 VolumeManager::~VolumeManager() {}
126
updateVirtualDisk()127 int VolumeManager::updateVirtualDisk() {
128 ATRACE_NAME("VolumeManager::updateVirtualDisk");
129 if (GetBoolProperty(kPropVirtualDisk, false)) {
130 if (access(kPathVirtualDisk, F_OK) != 0) {
131 Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
132 }
133
134 if (mVirtualDisk == nullptr) {
135 if (Loop::create(kPathVirtualDisk, mVirtualDiskPath) != 0) {
136 LOG(ERROR) << "Failed to create virtual disk";
137 return -1;
138 }
139
140 struct stat buf;
141 if (stat(mVirtualDiskPath.c_str(), &buf) < 0) {
142 PLOG(ERROR) << "Failed to stat " << mVirtualDiskPath;
143 return -1;
144 }
145
146 auto disk = new android::vold::Disk(
147 "virtual", buf.st_rdev, "virtual",
148 android::vold::Disk::Flags::kAdoptable | android::vold::Disk::Flags::kSd);
149 mVirtualDisk = std::shared_ptr<android::vold::Disk>(disk);
150 handleDiskAdded(mVirtualDisk);
151 }
152 } else {
153 if (mVirtualDisk != nullptr) {
154 dev_t device = mVirtualDisk->getDevice();
155 handleDiskRemoved(device);
156
157 Loop::destroyByDevice(mVirtualDiskPath.c_str());
158 mVirtualDisk = nullptr;
159 }
160
161 if (access(kPathVirtualDisk, F_OK) == 0) {
162 unlink(kPathVirtualDisk);
163 }
164 }
165 return 0;
166 }
167
setDebug(bool enable)168 int VolumeManager::setDebug(bool enable) {
169 mDebug = enable;
170 return 0;
171 }
172
start()173 int VolumeManager::start() {
174 ATRACE_NAME("VolumeManager::start");
175
176 // Always start from a clean slate by unmounting everything in
177 // directories that we own, in case we crashed.
178 unmountAll();
179
180 Loop::destroyAll();
181
182 // Assume that we always have an emulated volume on internal
183 // storage; the framework will decide if it should be mounted.
184 CHECK(mInternalEmulatedVolumes.empty());
185
186 auto vol = std::shared_ptr<android::vold::VolumeBase>(
187 new android::vold::EmulatedVolume("/data/media", 0));
188 vol->setMountUserId(0);
189 vol->create();
190 mInternalEmulatedVolumes.push_back(vol);
191
192 // Consider creating a virtual disk
193 updateVirtualDisk();
194
195 return 0;
196 }
197
handleBlockEvent(NetlinkEvent * evt)198 void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
199 std::lock_guard<std::mutex> lock(mLock);
200
201 if (mDebug) {
202 LOG(DEBUG) << "----------------";
203 LOG(DEBUG) << "handleBlockEvent with action " << (int)evt->getAction();
204 evt->dump();
205 }
206
207 std::string eventPath(evt->findParam("DEVPATH") ? evt->findParam("DEVPATH") : "");
208 std::string devType(evt->findParam("DEVTYPE") ? evt->findParam("DEVTYPE") : "");
209
210 if (devType != "disk") return;
211
212 int major = std::stoi(evt->findParam("MAJOR"));
213 int minor = std::stoi(evt->findParam("MINOR"));
214 dev_t device = makedev(major, minor);
215
216 switch (evt->getAction()) {
217 case NetlinkEvent::Action::kAdd: {
218 for (const auto& source : mDiskSources) {
219 if (source->matches(eventPath)) {
220 // For now, assume that MMC and virtio-blk (the latter is
221 // specific to virtual platforms; see Utils.cpp for details)
222 // devices are SD, and that everything else is USB
223 int flags = source->getFlags();
224 if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
225 flags |= android::vold::Disk::Flags::kSd;
226 } else {
227 flags |= android::vold::Disk::Flags::kUsb;
228 }
229
230 auto disk =
231 new android::vold::Disk(eventPath, device, source->getNickname(), flags);
232 handleDiskAdded(std::shared_ptr<android::vold::Disk>(disk));
233 break;
234 }
235 }
236 break;
237 }
238 case NetlinkEvent::Action::kChange: {
239 LOG(VERBOSE) << "Disk at " << major << ":" << minor << " changed";
240 handleDiskChanged(device);
241 break;
242 }
243 case NetlinkEvent::Action::kRemove: {
244 handleDiskRemoved(device);
245 break;
246 }
247 default: {
248 LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
249 break;
250 }
251 }
252 }
253
handleDiskAdded(const std::shared_ptr<android::vold::Disk> & disk)254 void VolumeManager::handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk) {
255 // For security reasons, if secure keyguard is showing, wait
256 // until the user unlocks the device to actually touch it
257 // Additionally, wait until user 0 is actually started, since we need
258 // the user to be up before we can mount a FUSE daemon to handle the disk.
259 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
260 if (mSecureKeyguardShowing) {
261 LOG(INFO) << "Found disk at " << disk->getEventPath()
262 << " but delaying scan due to secure keyguard";
263 mPendingDisks.push_back(disk);
264 } else if (!userZeroStarted) {
265 LOG(INFO) << "Found disk at " << disk->getEventPath()
266 << " but delaying scan due to user zero not having started";
267 mPendingDisks.push_back(disk);
268 } else {
269 disk->create();
270 mDisks.push_back(disk);
271 }
272 }
273
handleDiskChanged(dev_t device)274 void VolumeManager::handleDiskChanged(dev_t device) {
275 for (const auto& disk : mDisks) {
276 if (disk->getDevice() == device) {
277 disk->readMetadata();
278 disk->readPartitions();
279 }
280 }
281
282 // For security reasons, we ignore all pending disks, since
283 // we'll scan them once the device is unlocked
284 }
285
handleDiskRemoved(dev_t device)286 void VolumeManager::handleDiskRemoved(dev_t device) {
287 auto i = mDisks.begin();
288 while (i != mDisks.end()) {
289 if ((*i)->getDevice() == device) {
290 (*i)->destroy();
291 i = mDisks.erase(i);
292 } else {
293 ++i;
294 }
295 }
296 auto j = mPendingDisks.begin();
297 while (j != mPendingDisks.end()) {
298 if ((*j)->getDevice() == device) {
299 j = mPendingDisks.erase(j);
300 } else {
301 ++j;
302 }
303 }
304 }
305
addDiskSource(const std::shared_ptr<DiskSource> & diskSource)306 void VolumeManager::addDiskSource(const std::shared_ptr<DiskSource>& diskSource) {
307 std::lock_guard<std::mutex> lock(mLock);
308 mDiskSources.push_back(diskSource);
309 }
310
findDisk(const std::string & id)311 std::shared_ptr<android::vold::Disk> VolumeManager::findDisk(const std::string& id) {
312 for (auto disk : mDisks) {
313 if (disk->getId() == id) {
314 return disk;
315 }
316 }
317 return nullptr;
318 }
319
findVolume(const std::string & id)320 std::shared_ptr<android::vold::VolumeBase> VolumeManager::findVolume(const std::string& id) {
321 for (const auto& vol : mInternalEmulatedVolumes) {
322 if (vol->getId() == id) {
323 return vol;
324 }
325 }
326 for (const auto& disk : mDisks) {
327 auto vol = disk->findVolume(id);
328 if (vol != nullptr) {
329 return vol;
330 }
331 }
332 for (const auto& vol : mObbVolumes) {
333 if (vol->getId() == id) {
334 return vol;
335 }
336 }
337 return nullptr;
338 }
339
listVolumes(android::vold::VolumeBase::Type type,std::list<std::string> & list) const340 void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
341 std::list<std::string>& list) const {
342 list.clear();
343 for (const auto& disk : mDisks) {
344 disk->listVolumes(type, list);
345 }
346 }
347
forgetPartition(const std::string & partGuid,const std::string & fsUuid)348 int VolumeManager::forgetPartition(const std::string& partGuid, const std::string& fsUuid) {
349 std::string normalizedGuid;
350 if (android::vold::NormalizeHex(partGuid, normalizedGuid)) {
351 LOG(WARNING) << "Invalid GUID " << partGuid;
352 return -1;
353 }
354
355 bool success = true;
356 std::string keyPath = android::vold::BuildKeyPath(normalizedGuid);
357 if (unlink(keyPath.c_str()) != 0) {
358 LOG(ERROR) << "Failed to unlink " << keyPath;
359 success = false;
360 }
361 if (fscrypt_is_native()) {
362 if (!fscrypt_destroy_volume_keys(fsUuid)) {
363 success = false;
364 }
365 }
366 return success ? 0 : -1;
367 }
368
destroyEmulatedVolumesForUser(userid_t userId)369 void VolumeManager::destroyEmulatedVolumesForUser(userid_t userId) {
370 // Destroy and remove all unstacked EmulatedVolumes for the user
371 auto i = mInternalEmulatedVolumes.begin();
372 while (i != mInternalEmulatedVolumes.end()) {
373 auto vol = *i;
374 if (vol->getMountUserId() == userId) {
375 vol->destroy();
376 i = mInternalEmulatedVolumes.erase(i);
377 } else {
378 i++;
379 }
380 }
381
382 // Destroy and remove all stacked EmulatedVolumes for the user on each mounted private volume
383 std::list<std::string> private_vols;
384 listVolumes(VolumeBase::Type::kPrivate, private_vols);
385 for (const std::string& id : private_vols) {
386 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
387 std::list<std::shared_ptr<VolumeBase>> vols_to_remove;
388 if (pvol->getState() == VolumeBase::State::kMounted) {
389 for (const auto& vol : pvol->getVolumes()) {
390 if (vol->getMountUserId() == userId) {
391 vols_to_remove.push_back(vol);
392 }
393 }
394 for (const auto& vol : vols_to_remove) {
395 vol->destroy();
396 pvol->removeVolume(vol);
397 }
398 } // else EmulatedVolumes will be destroyed on VolumeBase#unmount
399 }
400 }
401
createEmulatedVolumesForUser(userid_t userId)402 void VolumeManager::createEmulatedVolumesForUser(userid_t userId) {
403 // Create unstacked EmulatedVolumes for the user
404 auto vol = std::shared_ptr<android::vold::VolumeBase>(
405 new android::vold::EmulatedVolume("/data/media", userId));
406 vol->setMountUserId(userId);
407 mInternalEmulatedVolumes.push_back(vol);
408 vol->create();
409
410 // Create stacked EmulatedVolumes for the user on each PrivateVolume
411 std::list<std::string> private_vols;
412 listVolumes(VolumeBase::Type::kPrivate, private_vols);
413 for (const std::string& id : private_vols) {
414 PrivateVolume* pvol = static_cast<PrivateVolume*>(findVolume(id).get());
415 if (pvol->getState() == VolumeBase::State::kMounted) {
416 auto evol =
417 std::shared_ptr<android::vold::VolumeBase>(new android::vold::EmulatedVolume(
418 pvol->getPath() + "/media", pvol->getRawDevice(), pvol->getFsUuid(),
419 userId));
420 evol->setMountUserId(userId);
421 pvol->addVolume(evol);
422 evol->create();
423 } // else EmulatedVolumes will be created per user when on PrivateVolume#doMount
424 }
425 }
426
onUserAdded(userid_t userId,int userSerialNumber)427 int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
428 LOG(INFO) << "onUserAdded: " << userId;
429
430 mAddedUsers[userId] = userSerialNumber;
431 return 0;
432 }
433
onUserRemoved(userid_t userId)434 int VolumeManager::onUserRemoved(userid_t userId) {
435 LOG(INFO) << "onUserRemoved: " << userId;
436
437 onUserStopped(userId);
438 mAddedUsers.erase(userId);
439 return 0;
440 }
441
onUserStarted(userid_t userId)442 int VolumeManager::onUserStarted(userid_t userId) {
443 LOG(INFO) << "onUserStarted: " << userId;
444
445 if (mStartedUsers.find(userId) == mStartedUsers.end()) {
446 createEmulatedVolumesForUser(userId);
447 }
448
449 mStartedUsers.insert(userId);
450
451 createPendingDisksIfNeeded();
452 return 0;
453 }
454
onUserStopped(userid_t userId)455 int VolumeManager::onUserStopped(userid_t userId) {
456 LOG(VERBOSE) << "onUserStopped: " << userId;
457
458 if (mStartedUsers.find(userId) != mStartedUsers.end()) {
459 destroyEmulatedVolumesForUser(userId);
460 }
461
462 mStartedUsers.erase(userId);
463 return 0;
464 }
465
createPendingDisksIfNeeded()466 void VolumeManager::createPendingDisksIfNeeded() {
467 bool userZeroStarted = mStartedUsers.find(0) != mStartedUsers.end();
468 if (!mSecureKeyguardShowing && userZeroStarted) {
469 // Now that secure keyguard has been dismissed and user 0 has
470 // started, process any pending disks
471 for (const auto& disk : mPendingDisks) {
472 disk->create();
473 mDisks.push_back(disk);
474 }
475 mPendingDisks.clear();
476 }
477 }
478
onSecureKeyguardStateChanged(bool isShowing)479 int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
480 mSecureKeyguardShowing = isShowing;
481 createPendingDisksIfNeeded();
482 return 0;
483 }
484
485 // This code is executed after a fork so it's very important that the set of
486 // methods we call here is strictly limited.
487 //
488 // TODO: Get rid of this guesswork altogether and instead exec a process
489 // immediately after fork to do our bindding for us.
childProcess(const char * storageSource,const char * userSource,int nsFd,const char * name)490 static bool childProcess(const char* storageSource, const char* userSource, int nsFd,
491 const char* name) {
492 if (setns(nsFd, CLONE_NEWNS) != 0) {
493 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns for %s :%s", name,
494 strerror(errno));
495 return false;
496 }
497
498 // NOTE: Inlined from vold::UnmountTree here to avoid using PLOG methods and
499 // to also protect against future changes that may cause issues across a
500 // fork.
501 if (TEMP_FAILURE_RETRY(umount2("/storage/", MNT_DETACH)) < 0 && errno != EINVAL &&
502 errno != ENOENT) {
503 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to unmount /storage/ :%s",
504 strerror(errno));
505 return false;
506 }
507
508 if (TEMP_FAILURE_RETRY(mount(storageSource, "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
509 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
510 storageSource, name, strerror(errno));
511 return false;
512 }
513
514 if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
515 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
516 "Failed to set MS_SLAVE to /storage for %s :%s", name,
517 strerror(errno));
518 return false;
519 }
520
521 if (TEMP_FAILURE_RETRY(mount(userSource, "/storage/self", NULL, MS_BIND, NULL)) == -1) {
522 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s for %s :%s",
523 userSource, name, strerror(errno));
524 return false;
525 }
526
527 return true;
528 }
529
530 // Fork the process and remount storage
forkAndRemountChild(uid_t uid,pid_t pid,int nsFd,const char * name,void * params)531 bool forkAndRemountChild(uid_t uid, pid_t pid, int nsFd, const char* name, void* params) {
532 int32_t mountMode = *static_cast<int32_t*>(params);
533 std::string userSource;
534 std::string storageSource;
535 pid_t child;
536 // Need to fix these paths to account for when sdcardfs is gone
537 switch (mountMode) {
538 case VoldNativeService::REMOUNT_MODE_NONE:
539 return true;
540 case VoldNativeService::REMOUNT_MODE_DEFAULT:
541 storageSource = "/mnt/runtime/default";
542 break;
543 case VoldNativeService::REMOUNT_MODE_ANDROID_WRITABLE:
544 case VoldNativeService::REMOUNT_MODE_INSTALLER:
545 storageSource = "/mnt/runtime/write";
546 break;
547 case VoldNativeService::REMOUNT_MODE_PASS_THROUGH:
548 return true;
549 default:
550 PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
551 return false;
552 }
553 LOG(DEBUG) << "Remounting " << uid << " as " << storageSource;
554
555 // Fork a child to mount user-specific symlink helper into place
556 userSource = StringPrintf("/mnt/user/%d", multiuser_get_user_id(uid));
557 if (!(child = fork())) {
558 if (childProcess(storageSource.c_str(), userSource.c_str(), nsFd, name)) {
559 _exit(0);
560 } else {
561 _exit(1);
562 }
563 }
564
565 if (child == -1) {
566 PLOG(ERROR) << "Failed to fork";
567 return false;
568 } else {
569 TEMP_FAILURE_RETRY(waitpid(child, nullptr, 0));
570 }
571 return true;
572 }
573
574 // Helper function to scan all processes in /proc and call the callback if:
575 // 1). pid belongs to an app process
576 // 2). If input uid is 0 or it matches the process uid
577 // 3). If userId is not -1 or userId matches the process userId
scanProcProcesses(uid_t uid,userid_t userId,ScanProcCallback callback,void * params)578 bool scanProcProcesses(uid_t uid, userid_t userId, ScanProcCallback callback, void* params) {
579 DIR* dir;
580 struct dirent* de;
581 std::string rootName;
582 std::string pidName;
583 int pidFd;
584 int nsFd;
585 struct stat sb;
586
587 static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
588
589 if (!(dir = opendir("/proc"))) {
590 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to opendir");
591 return false;
592 }
593
594 // Figure out root namespace to compare against below
595 if (!android::vold::Readlinkat(dirfd(dir), "1/ns/mnt", &rootName)) {
596 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to read root namespace");
597 closedir(dir);
598 return false;
599 }
600
601 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Start scanning all processes");
602 // Poke through all running PIDs look for apps running as UID
603 while ((de = readdir(dir))) {
604 pid_t pid;
605 if (de->d_type != DT_DIR) continue;
606 if (!android::base::ParseInt(de->d_name, &pid)) continue;
607
608 pidFd = -1;
609 nsFd = -1;
610
611 pidFd = openat(dirfd(dir), de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
612 if (pidFd < 0) {
613 goto next;
614 }
615 if (fstat(pidFd, &sb) != 0) {
616 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to stat %s", de->d_name);
617 goto next;
618 }
619 if (uid != 0 && sb.st_uid != uid) {
620 goto next;
621 }
622 if (userId != static_cast<userid_t>(-1) && multiuser_get_user_id(sb.st_uid) != userId) {
623 goto next;
624 }
625
626 // Matches so far, but refuse to touch if in root namespace
627 if (!android::vold::Readlinkat(pidFd, "ns/mnt", &pidName)) {
628 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
629 "Failed to read namespacefor %s", de->d_name);
630 goto next;
631 }
632 if (rootName == pidName) {
633 goto next;
634 }
635
636 if (apexUpdatable) {
637 std::string exeName;
638 // When ro.apex.bionic_updatable is set to true,
639 // some early native processes have mount namespaces that are different
640 // from that of the init. Therefore, above check can't filter them out.
641 // Since the propagation type of / is 'shared', unmounting /storage
642 // for the early native processes affects other processes including
643 // init. Filter out such processes by skipping if a process is a
644 // non-Java process whose UID is < AID_APP_START. (The UID condition
645 // is required to not filter out child processes spawned by apps.)
646 if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
647 goto next;
648 }
649 if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
650 goto next;
651 }
652 }
653
654 // We purposefully leave the namespace open across the fork
655 // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
656 nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
657 if (nsFd < 0) {
658 async_safe_format_log(ANDROID_LOG_ERROR, "vold",
659 "Failed to open namespace for %s", de->d_name);
660 goto next;
661 }
662
663 if (!callback(sb.st_uid, pid, nsFd, de->d_name, params)) {
664 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed in callback");
665 }
666
667 next:
668 close(nsFd);
669 close(pidFd);
670 }
671 closedir(dir);
672 async_safe_format_log(ANDROID_LOG_INFO, "vold", "Finished scanning all processes");
673 return true;
674 }
675
676 // In each app's namespace, unmount obb and data dirs
umountStorageDirs(int nsFd,const char * android_data_dir,const char * android_obb_dir,int uid,const char * targets[],int size)677 static bool umountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
678 int uid, const char* targets[], int size) {
679 // This code is executed after a fork so it's very important that the set of
680 // methods we call here is strictly limited.
681 if (setns(nsFd, CLONE_NEWNS) != 0) {
682 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
683 return false;
684 }
685
686 // Unmount of Android/data/foo needs to be done before Android/data below.
687 bool result = true;
688 for (int i = 0; i < size; i++) {
689 if (TEMP_FAILURE_RETRY(umount2(targets[i], MNT_DETACH)) < 0 && errno != EINVAL &&
690 errno != ENOENT) {
691 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s: %s",
692 targets[i], strerror(errno));
693 result = false;
694 }
695 }
696
697 // Mount tmpfs on Android/data and Android/obb
698 if (TEMP_FAILURE_RETRY(umount2(android_data_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
699 errno != ENOENT) {
700 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
701 android_data_dir, strerror(errno));
702 result = false;
703 }
704 if (TEMP_FAILURE_RETRY(umount2(android_obb_dir, MNT_DETACH)) < 0 && errno != EINVAL &&
705 errno != ENOENT) {
706 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to umount %s :%s",
707 android_obb_dir, strerror(errno));
708 result = false;
709 }
710 return result;
711 }
712
713 // In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
714 // package dirs.
remountStorageDirs(int nsFd,const char * android_data_dir,const char * android_obb_dir,int uid,const char * sources[],const char * targets[],int size)715 static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
716 int uid, const char* sources[], const char* targets[], int size) {
717 // This code is executed after a fork so it's very important that the set of
718 // methods we call here is strictly limited.
719 if (setns(nsFd, CLONE_NEWNS) != 0) {
720 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to setns %s", strerror(errno));
721 return false;
722 }
723
724 // Mount tmpfs on Android/data and Android/obb
725 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
726 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
727 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
728 android_data_dir, strerror(errno));
729 return false;
730 }
731 if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
732 MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
733 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
734 android_obb_dir, strerror(errno));
735 return false;
736 }
737
738 for (int i = 0; i < size; i++) {
739 // Create package dir and bind mount it to the actual one.
740 if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
741 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
742 targets[i], strerror(errno));
743 return false;
744 }
745 if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
746 async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
747 sources[i], targets[i], strerror(errno));
748 return false;
749 }
750 }
751 return true;
752 }
753
getStorageDirSrc(userid_t userId,const std::string & dirName,const std::string & packageName)754 static std::string getStorageDirSrc(userid_t userId, const std::string& dirName,
755 const std::string& packageName) {
756 if (IsSdcardfsUsed()) {
757 return StringPrintf("/mnt/runtime/default/emulated/%d/%s/%s",
758 userId, dirName.c_str(), packageName.c_str());
759 } else {
760 return StringPrintf("/mnt/pass_through/%d/emulated/%d/%s/%s",
761 userId, userId, dirName.c_str(), packageName.c_str());
762 }
763 }
764
getStorageDirTarget(userid_t userId,std::string dirName,std::string packageName)765 static std::string getStorageDirTarget(userid_t userId, std::string dirName,
766 std::string packageName) {
767 return StringPrintf("/storage/emulated/%d/%s/%s",
768 userId, dirName.c_str(), packageName.c_str());
769 }
770
771 // Fork the process and remount / unmount app data and obb dirs
forkAndRemountStorage(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)772 bool VolumeManager::forkAndRemountStorage(int uid, int pid, bool doUnmount,
773 const std::vector<std::string>& packageNames) {
774 userid_t userId = multiuser_get_user_id(uid);
775 std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
776 android::base::unique_fd nsFd(
777 TEMP_FAILURE_RETRY(open(mnt_path.c_str(), O_RDONLY | O_CLOEXEC)));
778 if (nsFd == -1) {
779 PLOG(ERROR) << "Unable to open " << mnt_path.c_str();
780 return false;
781 }
782 // Storing both Android/obb and Android/data paths.
783 int size = packageNames.size() * 2;
784
785 std::unique_ptr<std::string[]> sources(new std::string[size]);
786 std::unique_ptr<std::string[]> targets(new std::string[size]);
787 std::unique_ptr<const char*[]> sources_uptr(new const char*[size]);
788 std::unique_ptr<const char*[]> targets_uptr(new const char*[size]);
789 const char** sources_cstr = sources_uptr.get();
790 const char** targets_cstr = targets_uptr.get();
791
792 for (int i = 0; i < size; i += 2) {
793 std::string const& packageName = packageNames[i/2];
794 sources[i] = getStorageDirSrc(userId, "Android/data", packageName);
795 targets[i] = getStorageDirTarget(userId, "Android/data", packageName);
796 sources[i+1] = getStorageDirSrc(userId, "Android/obb", packageName);
797 targets[i+1] = getStorageDirTarget(userId, "Android/obb", packageName);
798
799 sources_cstr[i] = sources[i].c_str();
800 targets_cstr[i] = targets[i].c_str();
801 sources_cstr[i+1] = sources[i+1].c_str();
802 targets_cstr[i+1] = targets[i+1].c_str();
803 }
804
805 for (int i = 0; i < size; i++) {
806 // Make sure /storage/emulated/... paths are setup correctly
807 // This needs to be done before EnsureDirExists to ensure Android/ is created.
808 auto status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
809 if (status != OK) {
810 PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
811 return false;
812 }
813 status = EnsureDirExists(sources_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
814 if (status != OK) {
815 PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
816 return false;
817 }
818 }
819
820 char android_data_dir[PATH_MAX];
821 char android_obb_dir[PATH_MAX];
822 snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
823 snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
824
825 pid_t child;
826 // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
827 // original vold process mount namespace.
828 if (!(child = fork())) {
829 if (doUnmount) {
830 if (umountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
831 targets_cstr, size)) {
832 _exit(0);
833 } else {
834 _exit(1);
835 }
836 } else {
837 if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
838 sources_cstr, targets_cstr, size)) {
839 _exit(0);
840 } else {
841 _exit(1);
842 }
843 }
844 }
845
846 if (child == -1) {
847 PLOG(ERROR) << "Failed to fork";
848 return false;
849 } else {
850 int status;
851 if (TEMP_FAILURE_RETRY(waitpid(child, &status, 0)) == -1) {
852 PLOG(ERROR) << "Failed to waitpid: " << child;
853 return false;
854 }
855 if (!WIFEXITED(status)) {
856 PLOG(ERROR) << "Process did not exit normally, status: " << status;
857 return false;
858 }
859 if (WEXITSTATUS(status)) {
860 PLOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
861 return false;
862 }
863 }
864 return true;
865 }
866
handleAppStorageDirs(int uid,int pid,bool doUnmount,const std::vector<std::string> & packageNames)867 int VolumeManager::handleAppStorageDirs(int uid, int pid,
868 bool doUnmount, const std::vector<std::string>& packageNames) {
869 // Only run the remount if fuse is mounted for that user.
870 userid_t userId = multiuser_get_user_id(uid);
871 bool fuseMounted = false;
872 for (auto& vol : mInternalEmulatedVolumes) {
873 if (vol->getMountUserId() == userId && vol->getState() == VolumeBase::State::kMounted) {
874 auto* emulatedVol = static_cast<android::vold::EmulatedVolume*>(vol.get());
875 if (emulatedVol) {
876 fuseMounted = emulatedVol->isFuseMounted();
877 }
878 break;
879 }
880 }
881 if (fuseMounted) {
882 forkAndRemountStorage(uid, pid, doUnmount, packageNames);
883 }
884 return 0;
885 }
886
abortFuse()887 int VolumeManager::abortFuse() {
888 return android::vold::AbortFuseConnections();
889 }
890
reset()891 int VolumeManager::reset() {
892 // Tear down all existing disks/volumes and start from a blank slate so
893 // newly connected framework hears all events.
894 for (const auto& vol : mInternalEmulatedVolumes) {
895 vol->destroy();
896 }
897 mInternalEmulatedVolumes.clear();
898
899 // Destroy and recreate all disks except that StubVolume disks are just
900 // destroyed and removed from both mDisks and mPendingDisks.
901 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
902 // their disk recreation on reset events should be handled from outside by
903 // calling createStubVolume() again.
904 for (const auto& disk : mDisks) {
905 disk->destroy();
906 if (!disk->isStub()) {
907 disk->create();
908 }
909 }
910 const auto isStub = [](const auto& disk) { return disk->isStub(); };
911 mDisks.remove_if(isStub);
912 mPendingDisks.remove_if(isStub);
913
914 updateVirtualDisk();
915 mAddedUsers.clear();
916 mStartedUsers.clear();
917
918 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
919 // with FUSE fds open.
920 abortFuse();
921 return 0;
922 }
923
924 // Can be called twice (sequentially) during shutdown. should be safe for that.
shutdown()925 int VolumeManager::shutdown() {
926 if (mInternalEmulatedVolumes.empty()) {
927 return 0; // already shutdown
928 }
929 android::vold::sSleepOnUnmount = false;
930 for (const auto& vol : mInternalEmulatedVolumes) {
931 vol->destroy();
932 }
933 for (const auto& disk : mDisks) {
934 disk->destroy();
935 }
936
937 mInternalEmulatedVolumes.clear();
938 mDisks.clear();
939 mPendingDisks.clear();
940 android::vold::sSleepOnUnmount = true;
941
942 return 0;
943 }
944
unmountAll()945 int VolumeManager::unmountAll() {
946 std::lock_guard<std::mutex> lock(mLock);
947 ATRACE_NAME("VolumeManager::unmountAll()");
948
949 // First, try gracefully unmounting all known devices
950 for (const auto& vol : mInternalEmulatedVolumes) {
951 vol->unmount();
952 }
953 for (const auto& disk : mDisks) {
954 disk->unmountAll();
955 }
956
957 // Worst case we might have some stale mounts lurking around, so
958 // force unmount those just to be safe.
959 FILE* fp = setmntent("/proc/mounts", "re");
960 if (fp == NULL) {
961 PLOG(ERROR) << "Failed to open /proc/mounts";
962 return -errno;
963 }
964
965 // Some volumes can be stacked on each other, so force unmount in
966 // reverse order to give us the best chance of success.
967 std::list<std::string> toUnmount;
968 mntent* mentry;
969 while ((mentry = getmntent(fp)) != NULL) {
970 auto test = std::string(mentry->mnt_dir);
971 if ((StartsWith(test, "/mnt/") &&
972 #ifdef __ANDROID_DEBUGGABLE__
973 !StartsWith(test, "/mnt/scratch") &&
974 #endif
975 !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
976 !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
977 StartsWith(test, "/storage/")) {
978 toUnmount.push_front(test);
979 }
980 }
981 endmntent(fp);
982
983 for (const auto& path : toUnmount) {
984 LOG(DEBUG) << "Tearing down stale mount " << path;
985 android::vold::ForceUnmount(path);
986 }
987
988 return 0;
989 }
990
ensureAppDirsCreated(const std::vector<std::string> & paths,int32_t appUid)991 int VolumeManager::ensureAppDirsCreated(const std::vector<std::string>& paths, int32_t appUid) {
992 int size = paths.size();
993 for (int i = 0; i < size; i++) {
994 int result = setupAppDir(paths[i], appUid, false /* fixupExistingOnly */,
995 true /* skipIfDirExists */);
996 if (result != OK) {
997 return result;
998 }
999 }
1000 return OK;
1001 }
1002
setupAppDir(const std::string & path,int32_t appUid,bool fixupExistingOnly,bool skipIfDirExists)1003 int VolumeManager::setupAppDir(const std::string& path, int32_t appUid, bool fixupExistingOnly,
1004 bool skipIfDirExists) {
1005 // Only offer to create directories for paths managed by vold
1006 if (!StartsWith(path, "/storage/")) {
1007 LOG(ERROR) << "Failed to find mounted volume for " << path;
1008 return -EINVAL;
1009 }
1010
1011 // Find the volume it belongs to
1012 auto filter_fn = [&](const VolumeBase& vol) {
1013 if (vol.getState() != VolumeBase::State::kMounted) {
1014 // The volume must be mounted
1015 return false;
1016 }
1017 if (!vol.isVisibleForWrite()) {
1018 // App dirs should only be created for writable volumes.
1019 return false;
1020 }
1021 if (vol.getInternalPath().empty()) {
1022 return false;
1023 }
1024 if (vol.getMountUserId() != USER_UNKNOWN &&
1025 vol.getMountUserId() != multiuser_get_user_id(appUid)) {
1026 // The app dir must be created on a volume with the same user-id
1027 return false;
1028 }
1029 if (!path.empty() && StartsWith(path, vol.getPath())) {
1030 return true;
1031 }
1032
1033 return false;
1034 };
1035 auto volume = findVolumeWithFilter(filter_fn);
1036 if (volume == nullptr) {
1037 LOG(ERROR) << "Failed to find mounted volume for " << path;
1038 return -EINVAL;
1039 }
1040 // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
1041 // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
1042 // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
1043 // on /storage/emulated/10 means /mnt/user/0/emulated/10
1044 const std::string lowerPath =
1045 volume->getInternalPath() + path.substr(volume->getPath().length());
1046
1047 const std::string volumeRoot = volume->getRootPath(); // eg /data/media/0
1048
1049 const int access_result = access(lowerPath.c_str(), F_OK);
1050 if (fixupExistingOnly && access_result != 0) {
1051 // Nothing to fixup
1052 return OK;
1053 }
1054
1055 if (skipIfDirExists && access_result == 0) {
1056 // It's safe to assume it's ok as it will be used for zygote to bind mount dir only,
1057 // which the dir doesn't need to have correct permission for now yet.
1058 return OK;
1059 }
1060
1061 if (volume->getType() == VolumeBase::Type::kPublic) {
1062 // On public volumes, we don't need to setup permissions, as everything goes through
1063 // FUSE; just create the dirs and be done with it.
1064 return fs_mkdirs(lowerPath.c_str(), 0700);
1065 }
1066
1067 // Create the app paths we need from the root
1068 return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
1069 }
1070
fixupAppDir(const std::string & path,int32_t appUid)1071 int VolumeManager::fixupAppDir(const std::string& path, int32_t appUid) {
1072 if (IsSdcardfsUsed()) {
1073 //sdcardfs magically does this for us
1074 return OK;
1075 }
1076 return setupAppDir(path, appUid, true /* fixupExistingOnly */);
1077 }
1078
createObb(const std::string & sourcePath,int32_t ownerGid,std::string * outVolId)1079 int VolumeManager::createObb(const std::string& sourcePath, int32_t ownerGid,
1080 std::string* outVolId) {
1081 int id = mNextObbId++;
1082
1083 std::string lowerSourcePath;
1084
1085 // Convert to lower filesystem path
1086 if (StartsWith(sourcePath, "/storage/")) {
1087 auto filter_fn = [&](const VolumeBase& vol) {
1088 if (vol.getState() != VolumeBase::State::kMounted) {
1089 // The volume must be mounted
1090 return false;
1091 }
1092 if (!vol.isVisibleForWrite()) {
1093 // Obb volume should only be created for writable volumes.
1094 return false;
1095 }
1096 if (vol.getInternalPath().empty()) {
1097 return false;
1098 }
1099 if (!sourcePath.empty() && StartsWith(sourcePath, vol.getPath())) {
1100 return true;
1101 }
1102
1103 return false;
1104 };
1105 auto volume = findVolumeWithFilter(filter_fn);
1106 if (volume == nullptr) {
1107 LOG(ERROR) << "Failed to find mounted volume for " << sourcePath;
1108 return -EINVAL;
1109 } else {
1110 lowerSourcePath =
1111 volume->getInternalPath() + sourcePath.substr(volume->getPath().length());
1112 }
1113 } else {
1114 lowerSourcePath = sourcePath;
1115 }
1116
1117 auto vol = std::shared_ptr<android::vold::VolumeBase>(
1118 new android::vold::ObbVolume(id, lowerSourcePath, ownerGid));
1119 vol->create();
1120
1121 mObbVolumes.push_back(vol);
1122 *outVolId = vol->getId();
1123 return android::OK;
1124 }
1125
destroyObb(const std::string & volId)1126 int VolumeManager::destroyObb(const std::string& volId) {
1127 auto i = mObbVolumes.begin();
1128 while (i != mObbVolumes.end()) {
1129 if ((*i)->getId() == volId) {
1130 (*i)->destroy();
1131 i = mObbVolumes.erase(i);
1132 } else {
1133 ++i;
1134 }
1135 }
1136 return android::OK;
1137 }
1138
createStubVolume(const std::string & sourcePath,const std::string & mountPath,const std::string & fsType,const std::string & fsUuid,const std::string & fsLabel,int32_t flags,std::string * outVolId)1139 int VolumeManager::createStubVolume(const std::string& sourcePath, const std::string& mountPath,
1140 const std::string& fsType, const std::string& fsUuid,
1141 const std::string& fsLabel, int32_t flags,
1142 std::string* outVolId) {
1143 dev_t stubId = --mNextStubId;
1144 auto vol = std::shared_ptr<android::vold::StubVolume>(
1145 new android::vold::StubVolume(stubId, sourcePath, mountPath, fsType, fsUuid, fsLabel));
1146
1147 int32_t passedFlags = 0;
1148 passedFlags |= (flags & android::vold::Disk::Flags::kUsb);
1149 passedFlags |= (flags & android::vold::Disk::Flags::kSd);
1150 if (flags & android::vold::Disk::Flags::kStubVisible) {
1151 passedFlags |= (flags & android::vold::Disk::Flags::kStubVisible);
1152 } else {
1153 passedFlags |= (flags & android::vold::Disk::Flags::kStubInvisible);
1154 }
1155 // StubDisk doesn't have device node corresponds to it. So, a fake device
1156 // number is used.
1157 auto disk = std::shared_ptr<android::vold::Disk>(
1158 new android::vold::Disk("stub", stubId, "stub", passedFlags));
1159 disk->initializePartition(vol);
1160 handleDiskAdded(disk);
1161 *outVolId = vol->getId();
1162 return android::OK;
1163 }
1164
destroyStubVolume(const std::string & volId)1165 int VolumeManager::destroyStubVolume(const std::string& volId) {
1166 auto tokens = android::base::Split(volId, ":");
1167 CHECK(tokens.size() == 2);
1168 dev_t stubId;
1169 CHECK(android::base::ParseUint(tokens[1], &stubId));
1170 handleDiskRemoved(stubId);
1171 return android::OK;
1172 }
1173
mountAppFuse(uid_t uid,int mountId,unique_fd * device_fd)1174 int VolumeManager::mountAppFuse(uid_t uid, int mountId, unique_fd* device_fd) {
1175 return android::vold::MountAppFuse(uid, mountId, device_fd);
1176 }
1177
unmountAppFuse(uid_t uid,int mountId)1178 int VolumeManager::unmountAppFuse(uid_t uid, int mountId) {
1179 return android::vold::UnmountAppFuse(uid, mountId);
1180 }
1181
openAppFuseFile(uid_t uid,int mountId,int fileId,int flags)1182 int VolumeManager::openAppFuseFile(uid_t uid, int mountId, int fileId, int flags) {
1183 return android::vold::OpenAppFuseFile(uid, mountId, fileId, flags);
1184 }
1185