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