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